I am trying to share service data between parent/child components in angular 4. I have a working code but I am not clear if thats the best option. I am using an injectable service class to communicate between parent --> child by creating Subjects and subscribing to observable methods. Now to communicate backwards i:e child --> parent, I am re-using the same service class by creating Subjects and subscribing to observable in parent. That way I am subscribing to observables in both child and parent, is it the right approach? I have seen elsewhere that people have suggested @Output decorator to communicate between child --> parent, but my code is working with the subscribe mechanism. Will it cause any issues in future like memory leakage?
Parent Component
constructor(private _textdataservice: TinyEditorService, private _gmapService: GmapService) {
this.subscription = this._gmapService.getMessageC2P().subscribe((message) => {
this.message = message;
this.childCallingParent(message);
});
this.subscription = this._gmapService.getStoreSearchRequest().subscribe((radius) => {
this.radius = radius;
this.retrieveNearByLocations(radius);
});
}
Child Component -->
constructor(private _gmapService: GmapService) {
// subscribe to home component messages
this.mainSubscription = this._gmapService.getMessageP2C().subscribe((addresses) => {
this.mainCoordinates = addresses;
});
this.storeSubscription = this._gmapService.getMessageP2CStore().subscribe((addresses) => {
this.storeCoordinates = addresses;
if(this.storeCoordinates){
for(let coord of this.storeCoordinates){
this.addNearbyStoremarker(coord.name, coord.latitude, coord.longitude);
}
}
});
}
Service -->
export class GmapService {
private _dataurl='/assets/gmapmarkers.json';
constructor(private _http: Http){}
private parentSubject = new Subject<IGmapData[]>();
private storeSubject = new Subject<IGmapData[]>();
private childSubject = new Subject<String>();
private radiusSubject = new Subject<number>();
sendMessageP2C(latLngArray: IGmapData[]) {
this.parentSubject.next(latLngArray);
}
sendMessageP2CStore(latLngArray: IGmapData[]) {
this.storeSubject.next(latLngArray);
}
sendMessageC2P(message: string) {
this.childSubject.next(message);
}
requestNearByLocations(radius: number) {
this.radiusSubject.next(radius);
}
clearMessage() {
this.parentSubject.next();
this.childSubject.next();
}
getMessageP2C(): Observable<IGmapData[]> {
return this.parentSubject.asObservable();
}
getMessageP2CStore(): Observable<IGmapData[]> {
return this.storeSubject.asObservable();
}
getMessageC2P(): Observable<string> {
return this.childSubject.asObservable();
}
getStoreSearchRequest(): Observable<number> {
return this.radiusSubject.asObservable();
}
getStoreMarkers(): Observable<IGmapData[]> {
return this._http.get(this._dataurl)
.map((response: Response) => <IGmapData[]> response.json());
}
}