如何使用Angular中的异步管道对可观察到的列表执行CRUD操作?

时间:2019-07-20 10:36:11

标签: angular typescript rxjs

到目前为止,在我的Angular应用程序中,我已经习惯使用ngFor指令来迭代列表,而不使用async管道。但是今天,我已经了解了async管道并尝试实现它们。

所以这是我的示例组件模板:

<ng-container *ngIf="todos$ | asyc as todos">
  <div *ngFor="let todo of todos">{{ todo.content }}</div>
</ng-container>

在示例组件类上

this.todos$ = this.todoService.getAllTodos();

我要弄清楚的是如何在可观察的todos$上添加,编辑或删除操作。

1 个答案:

答案 0 :(得分:0)

首先httpClient的请求是自完成的,这意味着在请求完成后,它不能发出任何新值。

解决方案是使用单独的Observable或Subject。在这种情况下,一个不错的候选人会BehaviourSubject

首先定义

this.todos$ = new BehaviourSubject(null);

请注意,nulltodos$的默认值。您可以传递一个空数组来摆脱*ngIf

然后在请求完成后发出响应:

this.todoService.getAllTodos()
  .subscribe(response => {
    this.todos$.next(response);
  });

将来,如果您想更改数据,则可以从BehaviourSubject获取当前值,对其进行转换并重新提交,例如添加一个项目将是:

this.todos$.next([newItem, ...this.todos$.value]);