【问题标题】:ActivatedRoute observable with manual refresh ability具有手动刷新能力的ActivatedRoute observable
【发布时间】:2021-03-05 07:57:58
【问题描述】:

我目前正在开发一个需要手动“从服务器重新获取”功能的 Angular 组件。

下面列出的版本有效,但有什么方法可以简化它?看起来有点复杂。

private refreshSignalSubject = new Subject<any>();
refreshSignal$: Observable<any> = this.refreshSignalSubject.asObservable();

ngOnInit() {
  this.item$ = combineLatest(
    this.route.paramMap.pipe(
      map(params => params.get('id')),
    ),
    this.refreshSignal$.pipe(
      startWith(() => Math.random())
    )
  ).pipe(
    map((values) => {
      const [id, _] = values
      return id
    }),
    switchMap(id => this.apiService.get(`/items/${id}`)),
    share()
  )
}

reloadItem() { // this method is triggered from the view and from other methods in this component
  this.refreshSignalSubject.next(Math.random());
}

【问题讨论】:

    标签: angular rxjs rxjs-observables


    【解决方案1】:

    你甚至不需要把它放在ngOnInit

    readonly items$ = combineLatest([
      this.route.params.pipe(
        map(({ id }) => id),
        distinctUntilChanged()
      ),
      this.refreshSignal$
    ]).pipe(
      switchMap(([ id ]) => this.apiService.get(`/items/${id}`)),
      shareReplay(1)
    )
    

    应该够了

    【讨论】:

    • 我必须将startWith 添加到refreshSignal$,否则看起来不错。谢谢
    • @NikitaFedyashev:在这种情况下,为什么不把refreshSignalSubject 变成BehaviorSubject?这将减少对startWith 的需求。
    • @NikitaFedyashev 正如迈克尔所说使用BehaviorSubject。或者你可以在ngOnInit中拨打reloadItem()
    猜你喜欢
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 2018-11-20
    • 2018-09-16
    • 2021-07-04
    • 1970-01-01
    • 2012-11-22
    相关资源
    最近更新 更多