angular - 重新分配通过异步管道使用的 Observable

标签 angular

假设在我的 Component 中我有一个 Observable 字段,它是通过 Service 检索的,它使用 HttpClient

@Component(...)
export class MyComponent {
  items$: Observable<readonly Item[]>;

  ngOnInit() {
    this.items$ = this.findItems();
  }

  private findItems() {
    return this.service
      .getItems(...)
      .pipe(
        // Other code omitted
        toArray<Item>()
      );
  }
}

<app-items [items]="items$ | async"></app-items>

然后,当在 MyComponent 中执行操作时,我需要刷新 items$ 列表,因此我调用了 Service

onButtonPressed() {
  this.items$ = this.findItems();
}

问题是,Async 管道会自动订阅新的 Observable 吗?
考虑到我采用的是 OnPush 策略,是否需要请求 detectChanges()
最重要的是,这是正确的方法吗?

最佳答案

您可能想要使用 switchMap管道:

@Component(...)
export class MyComponent {
  items$: Observable<readonly Item[]>;

  updater$: Subject<void> = new Subject<void>();

  ngOnInit() {
    this.items$ = this.updater$
      .pipe(
        switchMap<void, Observable<Items[]>>(() => this.findItems())
      )
  }

  onButtonPressed(){
    this.updater$.next();
  }

  private findItems() {
    return this.service
      .getItems(...)
      .pipe(
        // Other code omitted
        toArray<Item>()
      );
  }
}

并且仍然使用:

<app-items [items]="items$ | async"></app-items>

switchMap()允许您拥有一个“永不重新分配”的可观察对象(updater$),并且对于此流上的每个发射度,它“切换”可观察对象的发射值以发送内部函数的结果,这应该是一个可观察对象.

在这里,每次调用updater$.next() ,它“切换”发射的 void findItems() 的结果方法,这是您的项目数组。

switchMap之间的区别和 mergeMap是那个switchMap负责完成和关闭之前发出的可观察对象。如果您调用 updater$.next()两次,第二次调用switchMap将完成第一次调用 findItems() 返回的第一个可观察对象并用此方法的新调用替换它。

来源:
https://www.learnrxjs.io/operators/transformation/switchmap.html
https://blog.angular-university.io/rxjs-higher-order-mapping/

关于angular - 重新分配通过异步管道使用的 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55968247/

相关文章:

angular - 无法从 Angular 访问谷歌Firebase?

javascript - 将初始值设置为 Angular 表单组以进行测试

Angular2 组件模板与 View 模板

Angular 2 : How to get query params in matrix notation

html - style.scss 中的 Angular 样式并不总是被应用

Angular HttpClient 为零响应返回空值

angular - 在ubuntu中安装@angular/cli时出现错误

javascript - 检索 firestore 文档 ID 并添加到 html

angular - 无法监视 window.confirm()

html - 使用 Angular 进行条件 HTML 注释