【问题标题】:Angular rxjs multiple subscriptions to ajax response observable firing multiple ajax requestsAngular rxjs 对 ajax 响应的多个订阅可观察到触发多个 ajax 请求
【发布时间】:2021-11-04 20:46:32
【问题描述】:

我如何才能订阅从“父”管道传输的“子”可观察对象而不触发主 ajax 请求?

如有必要,请参阅StackBlitz 上的完整工作 MVP 示例。

@Component({
  selector: 'my-app',
  template: `
    <h3>{{ title$ | async }}</h3>
    <p>{{ value$ | async }}</p>
  `,
})
export class AppComponent implements OnInit {
  public response$: Observable<Response>;
  public title$: Observable<string>;
  public value$: Observable<string>;

  constructor(private fakeAjaxService: FakeAjaxService) {}

  ngOnInit(): void {
    // call the main ajax request to populate the response$ observable
    this.response$ = this.fakeAjaxService.request();
    // pluck the title from the response
    this.title$ = this.response$.pipe(pluck('title'));
    // pluck the value from the response
    this.value$ = this.response$.pipe(pluck('value'));
  }
}

感谢您的帮助!

【问题讨论】:

    标签: angular typescript rxjs observable


    【解决方案1】:

    您可以使用shareReplay() 来缓存结果,然后this.response$ 将变成一个热可观察对象,并且只会触发一个请求。

      ngOnInit(): void {
        this.response$ = this.fakeAjaxService.request().pipe(shareReplay());
        this.title$ = this.response$.pipe(pluck('title'));
        this.value$ = this.response$.pipe(pluck('value'));
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2018-07-31
      • 2016-06-26
      • 1970-01-01
      • 2020-03-03
      • 2018-04-29
      • 2017-03-21
      相关资源
      最近更新 更多