我已经构建了一个与 REST api 通信的 CRUD 应用程序,但还没有找到在删除一个项目后刷新视图的方法。我过去曾使用 router.navigate 在其他方法(例如 create 方法)之后更改视图,并且效果很好。
问题是调用 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);
});
}