Angular 2 - Route guard not working on browser refresh

前端 未结 3 2067
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 01:12

Having these routes defined in app.module.ts

...
{ path: \'mypath\', component: MyComponent, canActivate: [RouteGuard] }, 
{ path: \'\', redirectTo: \'/home\         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 01:16

    You're making an asynchronous call to your auth service, that means canActivate() returns this.loggedIn before it sets its value to true or false. And since the guard is called every time you take the 'mypath' route this.isLoggedin will be reset to null

    Now to avoid this behavior you can use a boolean outside of your guard and use that boolean to keep track of if you're logged in or not.

提交回复
热议问题