REST API と通信する CRUD アプリを作成しましたが、1 つのアイテムが削除された後にビューを更新する方法が見つかりません。私は過去に router.navigate を使用して、 create メソッドなどの他のメソッドの後にビューを変更しましたが、これは正常に機能します。
問題は、削除メソッドを呼び出すイベントがアイテムの同じリスト内にあることです (すべての *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);
});
}