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
令牌收到的值。
如何在該場景中組織我的代碼?
這可能有助於〜http://stackoverflow.com/questions/35498456/what-is-httpinterceptor-equivalent-in- angular2 – Phil