简体   繁体   English

Angular 2 Auth Guard中断重定向

[英]angular 2 Auth guard breaks redirect

This is my app-routing.module.ts : 这是我的app-routing.module.ts

const routes: Routes = [
  { path: '', redirectTo: '/app/elements', pathMatch: 'full' },
  {path: 'app', component:ElementsComponent, children:[
    { path: 'details/:id', component: ElementDetailComponent, canActivate:[AuthGuard]},
    { path: 'elements',     component: ElementListComponent, canActivate:[AuthGuard] },

    { path: 'user/signup',     component: SignupComponent },
    { path: 'user/login',     component: LoginComponent },
    { path: 'user/logout',     component: LogoutComponent }
  ]}

];
@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ],
  providers: [AuthGuard]
})
export class AppRoutingModule {}

As you can see for the path '' I am redirecting to /app/elements which is kind of my home page. 如您所见,路径''我正在重定向到/app/elements这是我的主页。 This was working fine until I implemented the AuthGuard which looks like: 在我实现AuthGuard之前,它一直运行良好,如下所示:

@Injectable()
export class AuthGuard implements CanActivate{

  public allowed: boolean;

  constructor(private af: AngularFire, private router: Router) { }


  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    this.af.auth.subscribe((auth) =>  {
      if(auth == null) {
        this.router.navigate(['/app/user/login']);
        this.allowed = false;
      } else {
        this.allowed = true;
      }
    });
    return this.allowed;
  }
}

Now, if the user is not logged in and goes to http://localhost:4200/ , the redirect works and it tries to go to http://localhost:4200/app/elements , the guard detects the user is not logged in and it redirects to the login page. 现在,如果用户未登录并转到http://localhost:4200/ ,则重定向有效,并且尝试转到http://localhost:4200/app/elements ,守护程序检测到用户未登录并重定向到登录页面。

The problem is if the user is logged in and tries to go to http://localhost:4200/ . 问题是用户是否登录并尝试访问http://localhost:4200/ In this case, nothing happens, the user stays at that URL with the page blank. 在这种情况下,什么也不会发生,用户停留在该URL空白页面。

Why the redirect is not working in that case? 为什么在这种情况下重定向不起作用? Is there a way to fix that? 有办法解决吗?

the canActivate returns before the firebase observable resolves, so canActivate will always return false, but canActivate can return a promise or an Observable. canActivate的前返回firebase观察到的议决,所以canActivate将始终返回false,但canActivate可以返回一个承诺或可观察到的。

that should work : 应该工作:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.af.auth
                  .map(auth => auth != null)      // null means not authenticated
                  .do(isAuthenticated => {   // change routes if not authenticated
                     if(!isAuthenticated) {
                       this.router.navigate(['/app/user/login']);
                     }
                  });

}

You can use a service that keeps the the state of the authentication. 您可以使用保留身份验证状态的服务。 After that just use a code without subscription. 之后,只需使用没有订阅的代码即可。 Because it's executed async and brakes the code. 因为它异步执行并制动了代码。

public canActivate() {      
    if (this.authService.isAuthenticated) 
      return true;
    this.router.navigate(['/app/user/login']);
    return false;
}

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

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