2016-07-31 80 views
1

我已經構建了一個CRUD應用程序與REST API進行通信,但沒有找到一種方法來刪除一個項目後刪除視圖。在過去使用router.navigate在其他方法(例如create方法)之後更改視圖並且工作正常。Angular 2刷新視圖沒有route.navigate

問題是,調用delete方法的事件在項目的同一列表中(每個* ngFor項都有自己的刪除事件)。因此,如果我刪除一個項目,然後使用router.navigate轉到當前視圖,則它什麼都不做,因爲您已經在那裏,因此如果沒有已刪除的項目,即使它已經工作,也不會看到視圖的更新版本。

是否有任何其他方式刷新視圖,而不使用route.navigate?

編輯:

我試圖實現ChangeDetectorRef,仍然沒有工作,雖然...

這裏的組件:

import { Component, OnInit, ChangeDetectorRef } from '@angular/core'; 
import { ApiNoticiasService } from './api-noticias.service'; 
import { ROUTER_DIRECTIVES } from '@angular/router'; 

@Component({ 
    moduleId: module.id, 
    selector: 'app-noticias', 
    templateUrl: 'noticias.component.html', 
    styleUrls: ['noticias.component.css'], 
    directives: [ROUTER_DIRECTIVES], 
    providers: [ApiNoticiasService] 
}) 
export class NoticiasComponent implements OnInit { 
    noticias: any; 

    constructor(
    private cd: ChangeDetectorRef, 
    private _apiNoticias: ApiNoticiasService) { } 

    ngOnInit() { 
    this._apiNoticias.getNoticias() 
     .then((noticias) => this.noticias = noticias) 
     .catch((err) => { 
     console.log(err); 
     }); 
    } 

    deleteNoticia(id){ 
    this._apiNoticias.deleteNoticia(id) 
     .catch((err) => { 
     console.log(err); 
     }); 
    this.cd.markForCheck(); 
    } 

} 

而且這是在服務的方法:

deleteNoticia(id) { 
    return this._http.delete('http://localhost:3000/noticias/' +id) 
     .map((response: Response) => response.json()) 
     .toPromise() 
     .catch((err: any) => { 
     console.log(err); 
     return Promise.reject(err); 
     }); 
    } 
+1

請問您可以爲REST通信服務和要刷新的組件添加代碼。 –

回答

3

您正在尋找的主題是變更檢測。官方文件似乎還沒有得到說明,但this blog post相當深入地解釋。

我猜你正在使用推式變化檢測,因爲默認檢查每個事件的一切,並應該自動捕獲你的刪除。您可以放棄這一點並回到默認設置,但是您會失去您希望從該設置中獲得的任何性能提升。

爲了保持推動變化檢測,與您的問題相關的部分大約是3/4。您需要在顯示該項目的組件中注入ChangeDetectorRef,並在發生刪除時調用markForCheck()

編輯: 在看到你的代碼時,你的問題實際上並不是你實際上更新了視圖中的數據。服務器可能已刪除該項目,但客戶端的本地副本仍然存在。

您需要手動刪除本地數據,方法是適當更改noticias,或者從服務器重新獲取整批文件,並使用新獲取的結果替換本地緩存,方法與您在ngOnInit中執行的操作相同。後面的選項必須在.then()的刪除承諾內完成,否則得到正確的結果將受到競爭條件的影響。

+0

我很確定我沒有以正確的方式實施它。仍然無法正常工作... – cerealex

+0

@cerealex原來你並沒有使用推送改變檢測。看我的編輯。 – Douglas

+0

我正在嘗試使用* ngIf =「刪除== noticia。id「,然後在刪除方法的末尾放入deleted = id,這樣它就會離開dom,但它似乎* ngIf在渲染後不會繼續監聽......無論如何, – cerealex

0

其實你的刪除功能應該是這樣的。

deleteNoticia(id){ 
    this._apiNoticias.deleteNoticia(id) 
     .catch((err) => { 
     console.log(err); 
     }); 
    this.cd.markForCheck(); 
    this.ngOnInit(); 
    } 

您需要再次調用ngOnInit()函數再次獲取列表。