2017-02-08 1 views
1

어떻게하면 데이터를 반환하는 HTTP 호출을 기다리는 생성자를 차단할 수 있습니까?완료 될 때까지 생성자에서 구독 호출을 차단하는 방법?

constructor() { 
    this.initRestData().subscribe(); 
    // wait for data to be read 
    this.nextStep(); 
} 

initRestData() 호출에 의해 검색된 데이터는 응용 프로그램의 다른 서비스/구성 요소에서 필요합니다. 시작시에만이 작업을 수행해야합니다. 이것을 처리하는 더 좋은 방법이 있다면 Observable도 괜찮을 것입니다.

답변

1

당신이 (가) subscribe 내부 또는 do - 연산자의 두 호출 체인 수 : 다른 서비스뿐만 아니라 this.nextStep()에 의존하는 경우를 들어

constructor() { 
    this.initRestData() 
    .do(receivedData => this.nextStep(receivedData)}) 
    .subscribe(); 
} 

을, 당신은 스트림으로로이를 구현해야한다 잘 :

private initialData$ = new BehaviorSubject<any>(null); 
constructor() { 
    this.initRestData() 
    .do(data => this.initialData$.next(data)) 
    .switchMap(() => this.nextStep()) 
    .subscribe(); 
} 

nextStep(): Observable<any> { 
    return this.initialData$ 
     .filter(data => data != null) 
     .take(1) 
     .map(data => { 
      // do the logic of "nextStep" 
      // and return the result 
     }); 
} 
+0

답변 주셔서 감사하지만 nextStep()은 다른 서비스에서 호출 할 수도 있습니다. 그 때까지는 iniRestData()가 완료되지 않았습니다. 다른 서비스가 호출되기 전에 응용 프로그램 시작 (또는 차단)시 초기화 할 수 있습니까? – Stefan

+0

그런 경우'this.nextStep()'을 스트림으로 처리해야합니다. - 대답을 업데이트 할게. – olsn

관련 문제