[英]How do I use BehaviorSubject class to redirect user on homepage after logging in, it doesn't seem to work properly
I am developing an IONIC 4 app, and want to authenticate user before they can go to homepage. 我正在开发IONIC 4应用程序,并希望在用户进入首页之前对其进行身份验证。 How do I avoid login screen flickering after successful authentication?
成功通过身份验证后,如何避免登录屏幕闪烁?
This is an IONIC 4 app, with angular 6 support. 这是IONIC 4应用程序,具有angular 6支持。 I am using storage to save JWT token to avoid user going to login screen each time they run the application.
我正在使用存储来保存JWT令牌,以避免用户每次运行应用程序时都进入登录屏幕。
app-routing.module.ts APP-routing.module.ts
{ path: 'home', canActivate: [AuthGuardService], loadChildren: './home/home.module#HomePageModule' }
app.component.ts app.component.ts
this.authenticationService.authenticationState.subscribe(state => {
if (state) {
console.log("inside if, state=" + state);
this.router.navigate(['home'], {skipLocationChange: true});
} else {
console.log("inside else, state=" + state);
this.router.navigate(['signup1'], {skipLocationChange: true});
}
});
authentication.service.ts authentication.service.ts
const TOKEN_KEY = 'auth-token';
authenticationState = new BehaviorSubject(false);
constructor(private storage: Storage, private plt: Platform) {
this.plt.ready().then(() => {
this.checkToken();
});
}
checkToken() {
this.storage.get(TOKEN_KEY).then(res => {
if (res) {
this.authenticationState.next(true);
}
})
}
isAuthenticated() {
return this.authenticationState.value;
}
login() {
return this.storage.set(TOKEN_KEY, 'Bearer 1234567').then(() => {
this.authenticationState.next(true);
});
}
auth-gaurd.service.ts AUTH-gaurd.service.ts
canActivate(): boolean {
return this.auth.isAuthenticated();
}
The app should redirect user to home page after getting JWT token in storage without displaying login page. 在存储中获得JWT令牌后,该应用应将用户重定向到首页,而不显示登录页面。 However, it flickers login screen and then redirects to homepage.
但是,它会闪烁登录屏幕,然后重定向到主页。
Please check the output on my device 请检查我设备上的输出
https://drive.google.com/file/d/1Qz_1ExUB1d_I0r71sQ2sX1F4RFC5680E/view?usp=drivesdk https://drive.google.com/file/d/1Qz_1ExUB1d_I0r71sQ2sX1F4RFC5680E/view?usp=drivesdk
Ok i think i got, so you can try to change your subject to 好吧,我想我知道了,所以您可以尝试将您的主题更改为
authenticationState = new BehaviorSubject(null);
and in component: 并在组件中:
this.authenticationService.authenticationState.filter(x => x !== null).take(1).subscribe(...)
or using pipe 或使用管道
this.authenticationService.authenticationState.pipe(
filter(x => x !== null),
take(1)
).subscribe(...)
Hope that helps. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.