简体   繁体   English

Angular Authgaurd 登录后不重定向或强制应用程序到主页

[英]Angular Authgaurd not redirecting or forcing application to home page after login

Routing module路由模块

{
    path:'login',
  component:LoginComponent
    },
  {
  path: '',
  component: DefaultComponent,
 canActivate:[AuthGuard],
  children: [{
    path: '',
    component: DashboardComponent
  },

Login component.ts登录组件.ts

let hey=data["API Key"]
    let id=data["id"]
    console.log(id);
    console.log(hey);

    localStorage.setItem("key",hey),
  
    
    this.router.navigateByUrl('/');
    // window.location.reload(true)

Authgaurd.ts Authgaurd.ts

canActivate():boolean{
  if (this._authsevice.loggedIN()){
    return true
  }
  else{
    this._router.navigate(['/login'])
    return false
  }
}

Authservice.ts身份验证服务.ts

export class AuthService{

     loggedIN(){
         return !!localStorage.getItem('key')
     }
}

as soon as authenticated,it creates a key and stores it but i cant understand why the page is still being in login page without redirecting or navigating and forcing authservice to search for key一旦通过身份验证,它就会创建一个密钥并存储它,但我无法理解为什么该页面仍在登录页面中而没有重定向或导航并强制 authservice 搜索密钥
when i forcefully reload the page i still get the login page and with the second time authentication I'm able to access all the other pages当我强制重新加载页面时,我仍然获得登录页面,并且通过第二次身份验证,我能够访问所有其他页面

i dont understand why and how to force angular application to view once the key is being stored我不明白为什么以及如何在存储密钥后强制 angular 应用程序查看

you can return an URL tree, you should do:你可以返回一个 URL 树,你应该这样做:

canActivate(): boolean | UrlTree {
  if (this._authsevice.loggedIN()){
    return true
  }
  return this._router.navigate(['/login'])
}

to answer your question:回答你的问题:

use an Observable for your login state with a BehaviourSubject , you use Observable<boolean | UrlTre>使用Observable登录 state 和BehaviourSubject ,你使用Observable<boolean | UrlTre> Observable<boolean | UrlTre> as return value in canActivate . Observable<boolean | UrlTre>作为canActivate中的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM