2016-12-13 113 views
3

我正嘗試在Angular2 HTTP類的頂部創建一個使用API​​的類。最主要的是我需要添加自定義的auth頭,這是在用戶授權後可用的。是否有可能以某種方式同步調用異步Ionic Storage?

的主要問題是該令牌存儲在從它只能異步得到的離子性存儲模塊,但我需要返回的特定類型....

export class APIRequest extends Http { 

    private storage : Storage; 

    constructor (backend: XHRBackend, options: RequestOptions) { 
     super(backend, options); 

     this.storage = new Storage; 
    } 

    request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> { 
     if (typeof url === 'string') { 
      url = AppConfig.API_SERVER + url 
     } else { 
      url.url = AppConfig.API_SERVER + url.url 
     } 

     this.storage.get('authToken').then(token => { 
      if (typeof url === 'string') { 
       if (!options) { 
        options = {headers: new Headers()}; 
       } 

       options.headers.set('Authorization', `Bearer ${token}`); 
      } else { 
       url.headers.set('Authorization', `Bearer ${token}`); 
      } 
      // Here I need to return 
     }, err => { 
      // throw some error 
     }) 

     return super.request(url, options).catch(this.catchAuthError(this)); 
    } 
} 

所以基本上我需要以某種方式把return super.request(url, options)...承諾的存儲和返回時,我得到的令牌。

+0

你爲什麼不能使用''回報storage.get(),然後(FN)。然後(標記=> {返回super.request()})'' – raj

+0

@raj因爲':Observable ' – user1692333

+1

不是Observable的專家,但是如何使用'fromPromise'使得observable超出承諾,然後使用''flatMap''返回''request'' observale。 – raj

回答

5

接近成爲重複。 (Couln't找到它)

至少,答案可以應用於相同的問題。如果你想保持返回Observable修復將是您的Promisethis.storage.get)轉換爲Observable

之後,您可以使用像flapMap這樣的運算符返回值super.request

注意:編譯器不明白,它返回一個Response現在,所以更改返回類型Observable<any>(仍然會返回Response))

export class APIRequest extends Http { 

    private storage : Storage; 

    constructor (backend: XHRBackend, options: RequestOptions) { 
     super(backend, options); 

     this.storage = new Storage; 
    } 
    // any return type (will return Response object but compiler doesn't understand that) 
    request(url: string|Request, options?: RequestOptionsArgs): Observable<any> { 
     if (typeof url === 'string') { 
      url = AppConfig.API_SERVER + url 
     } else { 
      url.url = AppConfig.API_SERVER + url.url 
     } 

     //convert the Promise to an Observable 
     val storageObservable = Observable.fromPromise(this.sotrage.get('authToken')); 

     // rxjs/add/operator/mergeMap 
     return storageObservable.flatMap(token => { 
      if (typeof url === 'string') { 
       if (!options) { 
        options = {headers: new Headers()}; 
       } 

       options.headers.set('Authorization', `Bearer ${token}`); 
      } else { 
       url.headers.set('Authorization', `Bearer ${token}`); 
      } 
      // the value that will be returned 
      return super.request(url, options).catch(this.catchAuthError(this)); 
     }, err => { 
      // throw some error 
     }) 


    } 
} 

相關鏈接:

+0

我覺得''return''丟失了? – raj

+0

@raj謝謝指出!你是對的,編輯答案 – Ivaro18

+0

但是它仍然會引發錯誤http://i.imgur.com/gi3NQuX.png – user1692333