Pass API data from one component into another component?
First of all, you can see that the console log in component is executed before fetching the data from the backend. This, because this is asynchronous, so it takes a while for the response to arrive.
Second problem, which is related to the same issue, i.e, this being asynchronous, is that you cannot return anything from subscribe, you need to return an Observable to your component and in the component subscribe, either doing it "manually" or then using the async pipe.
If you want to share data to other components after initially getting it another component, what you can do is to use a BehaviorSubject
, so declare this in your service:
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
//....
// don't use "any", type your data instead!
private apiData = new BehaviorSubject<any>(null);
public apiData$ = this.apiData.asObservable();
fetchData() {
return this.http.get('/api/data').map((data) => {
return data.json();
})
}
// here we set/change value of the observable
setData(data) {
this.apiData.next(data)
}
and in the component where you are fetching the data and want to broadcast to other components, do...
this.dataService.fetchData()
.subscribe(data => {
this.data = data;
// set data in service which is to be shared
this.dataService.setData(data)
})
So now we have in this initial component fetched the data, and setting the data in service, which is broadcast to all other components that need it. In those components you just subscribe to this observable.
constructor(private dataService: DataService) {
dataService.apiData$.subscribe(data => this.data = data)
}
This solution is based on the idea that you have one component that initially gets the data and then shares it with other components.