0

路由模块

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

登录组件.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

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

身份验证服务.ts

export class AuthService{

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

一旦通过身份验证,它就会创建一个密钥并存储它,但我无法理解为什么该页面仍在登录页面中,而没有重定向或导航并
在我强制重新加载页面时强制 authservice 搜索密钥我仍然得到登录页面并使用第二次身份验证我可以访问所有其他页面

我不明白为什么以及如何在存储密钥后强制角度应用程序查看

4

1 回答 1

0

你可以返回一个 URL 树,你应该这样做:

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

回答你的问题:

使用 aObservable作为登录状态,BehaviourSubject使用aObservable<boolean | UrlTre>作为返回值canActivate

于 2020-08-13T18:02:36.017 回答