アングル4の親子コンポーネント間でサービスデータを共有しようとしています。動作するコードがありますが、最適なオプションがあるかどうかはわかりません。サブジェクトを作成し、観察可能なメソッドにサブスクライブすることで、parent - > child間の通信に注射可能なサービスクラスを使用しています。親子でobservableにサブスクライブすることで、同じサービスクラスを再利用しています。そうすれば、私は子供と親の両方で観察可能なものを購読しています。それは正しいアプローチですか?私は他の人が@Outputデコレータをchild - > parentの間でやりとりするように提案していますが、私のコードはsubscribeメカニズムで動作しています。メモリリークのような問題は今後発生しますか?角4コンポーネント通信 - サブスクライバとの親から子へ
親コンポーネント
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);
});
}
チャイルドコンポーネント - >
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);
}
}
});
}
サービス - >
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());
}
}
thx – whizKid
あなたは大歓迎です! – Mehdi