我已經構建了一個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);
});
}
請問您可以爲REST通信服務和要刷新的組件添加代碼。 –