1

我已经构建了一个与 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);
      });
  }
4

2 回答 2

3

您正在寻找的主题是变更检测。官方文档似乎还没有过多地谈论它,但是这篇博客文章相当深入地解释了它。

我猜您正在使用推送更改检测,因为默认值会检查每个事件的所有内容,并且应该已经自动捕获您的删除。您可以放弃它并恢复默认设置,但您会失去希望从该设置中获得的任何性能提升。

为了继续进行推送更改检测,与您的问题相关的部分大约在页面下方的 3/4 处。您需要将 aChangeDetectorRef注入显示该项目的组件中,并markForCheck()在删除发生时调用它。

编辑:在查看您的代码时,您的问题实际上是您实际上并没有更新视图中的数据。服务器可能已删除该项目,但客户端的本地副本仍然存在。

您将需要通过适当更改手动删除本地数据noticias,或者从服务器重新获取整个批次并用新获取的结果替换本地缓存,就像您在ngOnInit. 后一个选项必须.then()在删除承诺的内部完成,否则获得正确的结果将受制于竞争条件。

于 2016-07-31T21:35:14.720 回答
0

实际上你的删除功能应该是这样的。

deleteNoticia(id){
    this._apiNoticias.deleteNoticia(id)
      .catch((err) => {
      console.log(err);
      });
    this.cd.markForCheck();
    this.ngOnInit();
  }

您需要再次调用 ngOnInit() 函数才能再次获取列表。

于 2017-08-08T06:37:05.513 回答