Angular rxjs 多个订阅 ajax 响应可观察触发多个 ajax 请求

Angular rxjs multiple subscriptions to ajax response observable firing multiple ajax requests

我怎样才能订阅从“父级”传输的“子级”可观察对象而不触发主 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'));
  }
}

感谢您的帮助!

您可以使用 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'));
  }