我已经构建了一个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通信服务和要刷新的组件添加代码。 –