[英]I am trying to see if the user is logged in and if not push them to the login page
我正在嘗試使用ionViewWillEnter檢查用戶是否已登錄。如果返回false,則將其定向到登錄頁面。 然后我要調用intializeapp函數。 我對Angular和Ionic還是比較陌生,因此任何技巧都將有所幫助。 `
ionViewCanEnter() {
console.log("1");
console.log(this.userSevice.isUserLoggedIn());
if (this.userSevice.isUserLoggedIn() === false){
this.nav.push(LoginPage);
alert("user is logging in");
}
else{
this.initializeApp();
}
}`
angular中有一個漂亮的概念叫做Guard
,您可以使用它來處理您在angular應用程序中的整個登錄流程。
您可以創建一個身份驗證保護,並將其放置在路由器中或任何地方,並在用戶未登錄並嘗試訪問站點的私有區域時強制其進入登錄頁面。
這是一個簡單的身份驗證防護
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthService) { }
canActivate(): Observable<boolean> | boolean {
// here check if this is first time call. If not return
// simple boolean based on user object from authService
// otherwise:
return this.authService.getAuthenticated.map(user => {
this.authService.setUser(user);
return user ? true : false;
})
}
}
在路由器中,您可以像這樣使用
const routes: Routes = [
{
path: '',
canActivate: [AuthGuardService],
runGuardsAndResolvers: 'always',
}
...
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.