2016-10-03 66 views
0

我正在使用離子2/角2如何在承諾內返回請求

我需要做一個http請求,但在我必須使用Ionic Storage獲取令牌之前。

我創建了一個類ApiRequest

import {Http, Headers, RequestOptions} from '@angular/http'; 
import {Injectable} from '@angular/core'; 
import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 
import { Storage } from '@ionic/storage'; 

@Injectable() 
export class ApiRequest { 

    access_token: string; 

    constructor(private http: Http, public storage: Storage) { 
     this.storage.get('access_token').then((value:any) => { 
      this.access_token = value; 
     }); 
    } 

    get(url) { 
     let headers = new Headers({ 
      // 'Content-Type': 'application/json', 
      'Authorization': 'Bearer ' + this.access_token, 
      'X-Requested-With': 'XMLHttpRequest' 
     }); 
     let options = new RequestOptions({ headers: headers }); 

     return this.http.get(url, options) 
      .map(res => res.json()); 

    } 

} 

然後我可以調用像

apiRequest.get(this.URL) 
     .subscribe(
      data => { 
       this.element= data; 
      }, 
      err => { 
       console.log(JSON.stringify(err)); 
      }); 

我的問題是,this.storage.get異步http.get異步也和我必須返回http.get,因爲我想調用subscribe以外的函數。

在這種情況下http.get被稱爲this.acess令牌收到的值。

如何在該場景中組織我的代碼?

+0

這可能有助於〜http://stackoverflow.com/questions/35498456/what-is-httpinterceptor-equivalent-in- angular2 – Phil

回答

2

這可能會實現(沒有嘗試過我自己):

@Injectable() 
export class ApiRequest { 

    access_token: string; 

    constructor(private http: Http, public storage: Storage) { 
     this.storagePromise = this.storage.get('access_token').then((value:any) => { 
      this.access_token = value; 
     }); 
    } 

    get(url) { 
     let headers = new Headers({ 
      // 'Content-Type': 'application/json', 
      'Authorization': 'Bearer ' + this.access_token, 
      'X-Requested-With': 'XMLHttpRequest' 
     }); 
     let options = new RequestOptions({ headers: headers }); 

     return this.storagePromise.then(
      return token => this.http.get(url, options) 
      .map(res => res.json()); 
     ); 
    } 
} 
apiRequest.get(this.URL) 
    .then(observable => 
     observable.subscribe(
     data => { 
      this.element= data; 
     }, 
     err => { 
      console.log(JSON.stringify(err)); 
     } 
    );