2017-11-29 25 views
0

내가 작업 코드가 각 4의 상위/하위 구성 요소 간의 서비스 데이터를 공유하려고하지만 최선의 선택 이잖아 경우 확실하지 오전과 부모 아이. 주제를 만들고 관찰 가능한 방법을 구독하여 부모 -> 자식 사이에서 의사 소통하기 위해 주사 가능한 서비스 클래스를 사용하고 있습니다. 이제 역방향으로 의사 소통을하기 위해 : child -> parent, Subject를 만들고 parent에서 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()); 
 
    } 
 
}

답변

1

나는 당신이 앞뒤로 부모와 자녀 간의 의사 소통을해야하는 경우 @Input()와 @Output()를 사용하는 것이 낫다는 것을 말할 것입니다. Angular가 구성 요소가 실제로 나타나거나 사라지면 구독을 파기/생성합니다. 부모/자녀 관계가없는 구성 요소를 통해 이벤트를 브로드 캐스팅해야하는 경우에 주제가 유용합니다. 제목 사용의 예는 페이스 북입니다. 메시지가 수신되면 페이지의 여러 부분이 서로 관련되지 않고 해당 이벤트에 반응합니다. 당신이 당신의 주제에서 탈퇴 ngOnDestroy을 구현하는 경우

그러나, 그 깔끔한 솔루션을 유지해야합니다. 제목 접근 방식을 사용하는 위험은 결국 앱에서 수 백 가지의 주제가 생성되어 성능 문제가 발생할 수 있습니다.

+0

thx. – whizKid

+0

여러분을 환영합니다! – Mehdi

0

이 답변에 설명 된대로 메모리 누수를 방지하기 위해 ngOnDestroy 라이프 사이클 후크에서 구독을 취소 할 수 있습니다 : 당신이 바로 @Output 및 EventEmitter를 사용하여이 추가적인 복잡성을 필요로하지 않는 [how to unsubscribe several subscriber in angular 2

는 그러나 아마입니다 좋은 생각.

+0

덕분에 .. 난 이미 부모와 자식 모두 ngOnDestroy을 사용하고 있습니다. 또한 온라인에서 단일 구현을 찾지 못했기 때문에 부모 - 자식 간의 2-way pub-sub가 좋은 아이디어가 아니라는 사실에 동의하십시오. @output 데코레이터를 사용할 수는 있지만 코드를 서비스 클래스의 한 위치에 보관하려고했습니다. 아이에서 출력 데코레이터를 사용해야합니까? – whizKid

+0

@Output 속성은 자식 구성 요소에 있지만, 외부 서비스가 아닌 자식과 부모간에 직접 데이터를 전달하는 경우에만 해당됩니다. 귀중한 통찰력을 얻으려면 –

0

@Input @Output 속도가 느려질 수 당신이 아이의 아이에서 통과 할 때 복잡하게 할 수 있습니다. 혹시 너무 다른 구성 요소에서 데이터를 사용하려는 경우

저장 방식은 더 유연하다. 답장을

+0

Store 당신은 서비스 접근 방식을 의미합니다 @vineet? – whizKid