如何获取打字稿http.get observable等待参数内联返回?

时间:2019-05-21 04:04:27

标签: typescript promise observable httprequest angular2-observables

好吧,所以我试图获得我正在调用的http.get调用,以等待返回参数之一(getUserToken)后再调用http.get函数。我不想在这里将它们链接在一起,因为我的调用函数getSomeData返回了一个observable,然后由其他许多函数调用。

getSomeData是需要返回getUserToken的那个,但是getUserToken始终为null,因为我没有正确执行诺言。很抱歉,我在这里看不到解决方案。

此函数开始通话,有很多函数可以进行此通话,我不想在这里进行任何更改。

displayData(){
 let mySubscription = this.getSomeData();
    mySubscription.subscribe(retJson => {
      if (retJson != null && retJson !== undefined){
        console.log(retJson);
      }
    });
}

这是返回http的调用。getUserToken中的问题位于此处。我需要http.get等待getUserToken()。

getSomeData(){
     let temporary = this.http.get(serviceUrl, getUserToken() ).map((response: Response) => {
       return response;
  });
return temporary;
}

问题是getUserToken对服务器进行了自己的调用,是否有办法将其包装在可观察或承诺中,可以在getSomeData调用内的http.get内联调用和解析?

getUserToken(){
     this.authenticationService.getToken()
            .subscribe(responseData => {
              if (responseData){
                let headers = new Headers({ 'Authorization': 'Bearer ' + responseData.token });
                return new RequestOptions({ headers: headers });
              }
            });
}


1 个答案:

答案 0 :(得分:1)

您可以使用switchMap来实现。

@Injectable()
class SomeClass {
   // Constructor omitted

   public displayData():void {
      const subscription:Subscription = this.getSomeData()
         .filter(retJson => !!retJson) // Only if json is truthy
         .subscribe(console.log);
   }

   // Get the user token, then switch to the actual data
   private getSomeData():Observable<any /*Replace with correct data type*/ > {
      return this.getUserToken() // get the user token
         .switchMap(userToken => // This is the token -> switchMap basically subscribes to the getUserToken and returns another observable
            this.http.get(serviceUrl, // switch to another observable as soon as getUserToken gives a value
               new RequestOptions({headers: new Headers({...userToken})}) // optionally, add other headers here
            )
         );
   }

   private getUserToken():Observable<{authorization: string}> {
      return this.authenticationService.getToken()
        .filter(responseData => !!responseData) // only if responseData is truthy
        .map(responseData => ({'Authorization': `Bearer ${responseData.token}`})); // Map to the object representing the header header
   }

}

或者,要使流更明显,可以在单个方法中这样编写(不推荐使用,只是暂时使流更明显):

const subscription:Subscription = this.authenticationService.getToken()
   .filter(responseData => !!responseData) // only if responseData is truthy
   .switchMap(userToken => // This is the token -> switchMap basically subscribes to the getUserToken and returns another observable
        this.http.get(serviceUrl, // switch to another observable as soon as getUserToken gives a value
           new RequestOptions({headers: new Headers({'Authorization': `Bearer ${responseData.token}`})}) // optionally, add other headers here
        )
    )
    .filter(retJson => !!retJson) // Only if json is truthy
    .subscribe(console.log);