2017-05-30 71 views
1

我有一個Ionic 2應用程序,我想在其中實現註銷功能。我想在本地存儲中將Json Web Token的值設置爲null,然後在設置值之後,將用戶發送到登錄頁面。等待Ionic 2打字本地存儲承諾在繼續之前解決

我遇到了一個問題,即在將用戶帶到登錄頁面之前,應用程序未在等待JWT的值設置。這是一個問題,因爲在登錄頁面上,如果有一個有效的JWT,我有一個自動登錄用戶的功能。由於程序沒有阻塞並等待存儲中設置的值,因此用戶在註銷後立即重新登錄。

在將用戶發送回登錄頁面之前,如何等待要設置的令牌值?

註銷功能:

logout() { 
this.storage.ready().then(() => { 
    this.storage.set('token', '').then(data => { 
     this.navCtrl.setRoot(LoginPage); 
    }); 
}); 

CheckAuthentication功能:

checkAuthentication() { 
return new Promise((resolve, reject) => { 
    this.storage.get('token').then((value) => { 

    this.token = value; 

    let headers = new Headers(); 
    headers.append('Authorization', this.token); 

    this.http.get('apiURL', { headers: headers }) 
     .subscribe(res => { 
     resolve(res); 

     }, (err) => { 
     reject(err); 
     }); 

    }); 

    }); 
    } 

IonViewWillLoad:

ionViewWillLoad(){ 
//Check if already authenticated 
    this.auth.checkAuthentication().then((res) => { 
     console.log("Already authorized"); 
     this.loading.dismiss(); 
     this.navCtrl.setRoot(HomePage); 
    }, (err) => { 
     console.log("Not already authorized"); 
     this.loading.dismiss(); 
    });} 

回答

1

有幾件事情,你可以在這裏做。

首先,我會重構代碼,使其更具可讀性。如果你看到我有如下功能,你會注意到我們正在利用自然給予我們的承諾,因爲我們可以將它們鏈接在一起,而無需嵌套我們的then()

checkAuthentication(),你不需要像你一樣創建Promise。您可以將http Observable作爲承諾返回。如果http呼叫成功,那麼承諾就會解決。如果http呼叫失敗,則由此產生的承諾將被拒絕。

最後,我會嘗試使用ionViewDidLoad而不是willLoad

logout() { 
 
    this.storage.ready() 
 
    .then(() => this.storage.set('token', '')) 
 
    .then(data => this.navCtrl.setRoot(LoginPage)) 
 
} 
 

 
checkAuthentication() { 
 
    return this.storage.get('token') 
 
    .then((value) => { 
 
     this.token = value; 
 

 
     let headers = new Headers(); 
 
     headers.append('Authorization', this.token); 
 

 
     return Observable.toPromise(
 
     this.http.get('apiURL', { headers: headers }) 
 
    ); 
 
    }); 
 
} 
 

 
ionViewDidLoad() { 
 
    this.auth.checkAuthentication() 
 
    .then((res) => { 
 
     console.log("Already authorized"); 
 
     this.loading.dismiss(); 
 
     this.navCtrl.setRoot(HomePage); 
 
    }) 
 
    .catch((err) => { 
 
     console.log("Not already authorized"); 
 
     this.loading.dismiss(); 
 
    }); 
 
}

+0

該問題與我在此處發佈的代碼無關。我單擊註銷按鈕時,我實現的註銷功能未運行。這是因爲我正在編輯錯誤的typecipt文件。不過謝謝你的重構建議。 –

0

在註銷功能應該令牌刪除,而不是將其設置爲空 ''。因爲註銷後令牌仍然存在於存儲器中。

this.storage.removeItem('token')