2016-07-31 86 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()函数再次获取列表。