2017-05-30 69 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')