我正在构建一个离子应用程序,该应用程序要求用户登录才能访问内容,目前我遇到了一个问题:该应用程序退出太容易了。
此刻,无论何时用户从rootPage中按回,应用程序都会立即退出。打开登录页面后,将再次显示登录页面,并擦除所有会话数据。
所以我现在有两个问题:
首先,ionic如何检测到用户正试图从rootPage退出并退出应用程序?我希望能够显示一个提示,询问用户在发生这种情况时是否一定要离开。我试过在调用ionViewCanLeave()时显示提示,但是后来我意识到即使我使用NavCtrl从根目录页面中推入另一页,该提示也会被调用。
第二,即使在手机退出应用程序后,如何保存用户个人资料和会话数据?这样,下次用户打开应用时,如果他们没有从上一个会话中注销,则可以立即登录。
答案 0 :(得分:0)
这里的东西很少:
保留用户数据(例如JWT等身份验证令牌)是您在“登录”周期中应该执行的操作。只需使用Ionic Storage作为解决方案。您可以在Google上搜索的许多指南中介绍了实现它的方式。示例: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()”,请确保该方法更新布尔值:
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();
});
答案 1 :(得分:0)
最后,我将这段代码片段注入到我的应用模块中,以实现我想要的
this.platform.registerBackButtonAction(() => {
if (this.nav.canGoBack()) {
this.nav.pop();
} else {
this.promptExit();
}
})
private promptExit() {
let alert = this.alertCtrl.create({
title: 'Exit?',
message: 'Do you want to exit My App?',
buttons: [
{
text: 'Cancel',
role: 'cancel'
},
{
text: 'Exit',
handler: () => {
// Insert whatever you need to do before exiting here
...
this.platform.exitApp())
}
}
]
});
alert.present();
}