2017-08-17 77 views
0

我有一個存儲設置爲ACCESS_TOKEN,當我得到它回到我第一次失敗離子存儲返回undefined第一次

提供商:

getLayMinisters(){ 
    console.log(this.access_token); 
    return this.http.get(
    this.api.url() + '/faith-leader/' + 'lay-ministers', 
    { 
     headers: new Headers({ "Authorization": "Bearer " + this.access_token }) 
    } 
    ) 
    .map(
    response => response.json() 
    ); 
} 

這是該文件

構造
access_token: any; 
layMinister_id: string; 

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

這是我第

getLayMinisters(){ 
    this.layMinisterProvider.getLayMinisters().subscribe(
     data => { 
     this.layMinisters = data; 
     } 
    ); 
} 

這是它上面

layMinisters = []; 

constructor(
    public navCtrl: NavController, 
    public navParams: NavParams, 
    public layMinisterProvider: LayMinisterProvider, 
    public alertCtrl: AlertController 
) {} 

ionViewDidLoad() { 
    this.getLayMinisters(); 
} 
ionViewWillEnter() { 
    // this.getLayMinisters(); 
} 

當頁面第一次運行時,它返回console.log(this.access_token)收益爲undefined,然後我得到的API的錯誤沒有響應。但是,當我再次單擊鏈接打開頁面時,它運行良好並打印access_token並運行api調用並打印所有數據

+0

'this.storage.get'是一個異步操作。這就像'setTimeout(()=> {},2000)' – echonax

回答

1

當您調用getLayMinisters()時,由於這些任務是異步的,因此access_token未定義,所以當你http.get可能this.storage.get()還沒有完成,因爲這是一個承諾,如果在http.get碼功能

setTimeout(()=>{ 
    console.log(this.access_token) 
},1000) 
與1000毫秒

也許可能會打印出來(這取決於的storage.get()承諾響應時間)。

要解決它,你可以在layMinisterProvider創建一個函數:

getToken(){ 
    return this.storage.get('access_token') 
} 

,並在頁面:

getLayMinisters() { 
    if(!this.layMinisterProvider.access_token){ 
     this.layMinisterProvider 
     .getToken() 
     .then((access_token) => { 
      this.layMinisterProvider.access_token = access_token; 
      this.getData(); 
     }) 
    }else{ 
     this.getData(); 
    } 
} 
getData(){ 
    this.layMinisterProvider 
       .getLayMinisters() 
       .subscribe(data => { 
        this.layMinisters = data; 
       }); 
} 

記住的提供者必須已ACCESS_TOKEN公衆。

+0

這很好用 – SCRATK

+0

分離責任,你可以把它放在服務中,因爲這是它的責任。對不起。 – SergioEscudero