在 android 和 iOS 上使用 angular 处理原生脚本中的注销



我是NativeScript和Angular的新手,所以我感谢任何帮助/指导。我正在运行 Angular 8.2.14 和 nativescript 6.2.2。

我正在开发一款适用于 iOS 和 Android 的应用程序,该应用程序基本上在用户登录后提供精心策划的任务列表和其他一些基本信息。

当应用启动时,用户会看到一个登录组件。用户通过身份验证后,将使用 nativescript-secure-storage 插件保存用户名、令牌和过期时间戳。我正在存储用户名和令牌,以便用户下次启动应用程序时不必再次登录。

然后,用户通过this.router.navigateByUrl("/dashboard");路由到仪表板。

我按照 nativescript 文档中的示例将仪表板上操作栏中的"后退"导航按钮替换为调用函数的注销按钮。这在iOS中完美运行。用户点击注销按钮,我清除存储在安全存储中的用户名和安全令牌。

问题是在Android中,用户有一个后退按钮,而且<actionItem>标签实际上并没有出现在操作栏中。

登录组件的本质是:

export class LoginComponent implements OnInit {
secureStorage = new SecureStorage();
constructor(private router: Router, private userService: UserService) {
this.user = new User();
}
ngOnInit() {
// Check to see if user has a saved session
var sessionUser = this.userService.checkSavedSession();
if (sessionUser.expires > now) {
this.router.navigateByUrl("/dashboard");
}
}
login() {
// Called when user taps submit on login view
this.userService.login(this.user)
.subscribe(
// If user authed store the session
this.secureStorage.set({
key: "appSession",
value: JSON.stringify({
uid: resp.uid,
expires: resp.exp,
token: resp.token
})
});
// Go to the dashboard
this.router.navigateByUrl("/dashboard");
);
}
}

仪表板视图:

<ActionBar title="Dashboard" class="action-bar">
<navigationButton text="Log Out" ios:visibility="collapsed" (tap)="logout()"></navigationButton>
<actionItem text="Log Out" android:visibility="collapsed" (tap)="logout()"></actionItem>
</ActionBar>
<AbsoluteLayout><!-- View content --></AbsoluteLayout>

仪表板组件包含一个注销功能,用于清除安全存储并将用户返回到登录名。

logout() {
this.secureStorage.removeAll().then(success => console.log("Cleared storage");
this.location.back();
}

我尝试弄乱订阅导航事件和位置事件,看看我是否可以检测到用户在仪表板上点击了后退按钮。我可以检测到它正在发生,但我也想通知用户他们即将注销并让他们有机会改变主意,因为他们实际上并没有单击注销按钮。我似乎无法弄清楚那部分。

任何帮助将不胜感激。

从登录导航到仪表板时,您可以清除历史记录。如果这样做,点击后退按钮将关闭应用程序,而不是将用户带回登录。

此外,您必须使用RouterExtensions而不是Angular的Router。

this.routerExtensions.navigateByUrl("/dashboard", {clearHistory: true});

您也可以侦听后退按钮 (activityBackPressed( 事件,如有必要,覆盖默认行为。有关详细信息,请参阅应用程序生命周期文档。

注意:我认为您不想通过后退按钮注销用户,如果您愿意,那么您可能宁愿将令牌存储在变量中而不是使用安全存储。安全存储通常用于使用户即使在应用程序重新启动后也能保持登录状态。

最新更新