这里的东西很少:
保留用户数据(例如 JWT 等身份验证令牌)是您应该在“登录”周期中执行的操作。只需使用Ionic Storage 作为解决方案。您可以通过谷歌搜索的许多指南中描述了您实现它的方式。示例:https://www.joshmorony.com/hybrid-app-developers-dont-store-your-users-passwords/
但实施细节取决于您拥有的身份验证服务/方法。
-
对于注销,在用户选择注销后将其带到“登录”页面通常是一种很好的做法。如果他们想在大多数现代平台上真正关闭应用程序,则不必通过从 navstack 中删除 rootPage 来实现(就像现代 iOS 通过点击主页关闭应用程序然后向上滑动,Android 有自己的方法)。
所以注销的实现可能如下:
- 侧栏菜单具有“注销”按钮
- 用户按下它,您的注销方法将执行必要的操作,例如:
logout() {
this.navCtrl.push('LoginPage');
this.storage.remove('sessionData');
this.inventory.clear();
if (!this.appIsOnDevice && "serviceWorker" in navigator) {
navigator.serviceWorker.getRegistrations().then(registrations => {
registrations.forEach(registration => {
registration.unregister();
});
});
}
if (this.appIsOnline && this.pushToken !== "") {
this.revokeFCMToken();
}
}
如果您仍想采用“提示”类型的方法来离开 rootPage,您可以使用您尝试利用“承诺”的导航守卫来探索选项:
ionViewCanLeave() {
return new Promise((resolve, reject) => {
let alert = this.alertCtrl.create({
title: 'Log out',
subTitle: 'Are you sure you want to log out?',
buttons: [
{
text: 'No',
role: 'cancel',
handler: () => {
reject();
}
},
{
text: 'Yes',
handler: () => {
alert.dismiss().then(() => {
resolve();
});
}
}
]
});
alert.present();
});
更新:因此,如果您只是“转到另一个页面”(推入新页面),上述代码也会触发,因此要使其按照您想要的方式工作,您可以执行以下操作:
- 有一个变量控制用户是否请求注销(简单的布尔值)
-
如果用户单击注销按钮,则指向注销方法 - (click) = "logout()",请确保此类方法更新布尔值:
注销(){
// 更改用户注销事件的标志:
this.logoutRequested = true;
// 其余的注销逻辑:
}
现在在导航守卫方法中,您可以简单地检查这个布尔状态
示例
ionViewCanLeave() {
// here we add this check - if logout is not requested - the page is free to leave (as in case where you push in new page into view:
if (!this.logoutRequested) return true;
// if that condition is not met and logoutRequested is true we proceed with modal via promise, but before that we can already reset flag:
this.logoutRequested = false;
return new Promise((resolve, reject) => {
let alert = this.alertCtrl.create({
title: 'Log out',
subTitle: 'Are you sure you want to log out?',
buttons: [
{
text: 'No',
role: 'cancel',
handler: () => {
reject();
}
},
{
text: 'Yes',
handler: () => {
alert.dismiss().then(() => {
resolve();
});
}
}
]
});
alert.present();
});