如何在承诺内返回请求

问题描述:

我正在使用离子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

这可能会实现(没有尝试过我自己):

@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)); 
     } 
    );