I want to subscribe to observable from http.get without triggering it because i want it to be triggered by some other commponent.
Currently, I am doing this:
shared.service.ts
getAllIcons(){
console.log('getting all icons');
return this.http.get(`http://localhost:3000/AllIcons`).map(function (response: Response) {
return response.json();
})
}
component1
this.sharedService.getAllIcons().subscribe(
(value) =>{console.log(value);});
}
what I want to achieve
shared.service.ts
_observableForAllImages: Observable<{}>;
getAllIcons(){
console.log('getting all icons');
return _observableForAllImages = this.http.get(`http://localhost:3000/AllIcons`).map(function (response: Response) {
return response.json();
})
}
component2
this.sharedService.getAllIcons().subscribe(
(value) =>{console.log(value);});
}
component1
//BUT THIS GIVES ERROR
this.sharedService._observableForAllImages.subscribe((value)=>{
console.log(value);
this.imageContainers = value.imageContainers;
});
**ERROR = TypeError: Cannot read property 'subscribe' of undefined**
Why do I want it?
I have a component called imageGridComponent. This component is called by various parent component using routing and imageGridComponent displays all the images corresponding to that parent. Therefore, I want parent to be the triggering component and child to be the data using component.
Edit: My question is not about sharing the result of a http call to various subscriptions. Rather its about a single subscription (in child component) receiving data from the service method which will be called by different parents. I have attached a schematic to explain it.