1

My components are as shown below:

user-app-component.html

<app-header></app-header>
<app-main-component></app-main-component>

app-main-component.html

<app-child></app-child>

In the app-child component, I receive data from an API, which I would like to be able to access inside the app-header component. Example shown below

app-child.ts

sharedApiData: any;

ngOnInit() {
  apiRequest.subscribe(response => {
    this.sharedApiData = response; // I want to access the 'sharedApiData' inside my app-header component
  })
}

Which is considered to be a "best practice" to achieve the scenario described? Using EventEmitters? Share the data using an Injectable service between the components? Any other way?

Thanks in advance.

NickAth
  • 1,089
  • 1
  • 14
  • 35
  • 1
    Use a service with a BehaviorSubject to cache the value: https://stackoverflow.com/questions/71180334/how-to-manage-service-member-initialization-with-data-retrieved-through-http-req/71182417#71182417 – wlf Feb 22 '22 at 00:59
  • @GRD Is that way preferred than using a shared injectable service between the components and set/get a member variable of the service? If yes, why? – NickAth Feb 22 '22 at 13:10
  • 1
    There is not any preferred way. Do as what best suited for your use case. Get/Set method called each time when change detection occurs. Subject way is good than get/set method. For more discussion please do connect by email. Thanks! – GRD Feb 22 '22 at 15:36

0 Answers0