1

How can I make it so I can subscribe to the "child" observables piped from the "parent" without firing the main ajax request?

Please see full working MVP example on StackBlitz if necessary.

@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'));
  }
}

Thanks for any help!

1 Answer 1

2

You can use shareReplay() to cache the result then this.response$ will turn into a hot observable and only one request will trigger.

  ngOnInit(): void {
    this.response$ = this.fakeAjaxService.request().pipe(shareReplay());
    this.title$ = this.response$.pipe(pluck('title'));
    this.value$ = this.response$.pipe(pluck('value'));
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.