2017-05-22 2 views
3

내가 가지고 상황 재산 이제각도 2 - 구독 대 바인딩

@Injectable() 
export class MyService { 
    constructor(private _http: Http) {} 

    // a variable/getter in service that holds context 
    _currentContext: any; 
    get currentContext() { return this._currentContext;} 

    // a method in service that fetches context 
    fetchContext() { 
    return this._http.get(`/api/xxx`).map(response => response.json()); 
} 

구성 요소가이 서비스를 주입 할 수 있으며, 구성 요소 템플릿의 요소를 직접 상황 결합 할 수를 유지하는 서비스 . 컨텍스트가 변경 될 때마다 이러한 바인딩은 변경 감지의 일부로 업데이트됩니다.

컨텍스트가 변경 될 때 구성 요소에서 일부 논리를 실행하려면 어떻게해야합니까?

@Component({ 
    selector: 'my-cmp', 
    template: `<div *ngIf="_myService.currentContext` >asdf</div> 
}) 
export class MyComponent{ 
    constructor(private _myService: MyService) {} 

    //doSomethingOnContextChange(){} 
} 

나는 대답이 생성/내 서비스에 관찰 가능한을 유지하는 것입니다 생각하고 내 구성 요소는 관찰에 등록합니다.

_currentContextObservable= new Subject<any>(); 
get currentContextObservable(): Observable<any> { return this._currentContextObservable; } 

이렇게 변수마다 하나의 변수/getter와 하나의 subject/observable을 유지해야합니까? 아니면 다른 우아하고 좋은 방법이 있습니까?

+2

그렇게하는 방법입니다. –

+0

상대적으로 분리 된 서비스의 경우'context' 변수와'context $'를 모두 관찰 가능하게 유지하는 것이 도움이되므로 언제든지 선택할 수 있습니다. '상황'의 적합성 여부는 관측 대상이 차거나 뜨거워 야하는지 여부에 달려 있습니다 (이 예에서는 관측 대상이 구독되는 위치가 표시되지 않지만이 부분은 중요하지만 매우 중요합니다). – estus

+0

은 ngrx를 사용하고 여러 속성이있는 저장소를 정의합니다. –

답변

1

나는 종종 서비스의 종류 BehaviorSubject를 사용

export class MyService { 
    private contextSubject = new BehaviorSubject<any>(null); 
    context$ = this.contextSubject.asObservable(); 

    get context() { 
     return this.contextSubject.value; 
    } 

    ... 
} 

당신도 context 또는 context$는 당신이 필요에 따라 사용할 수 있습니다.