2


我正在使用 Angular 开发一个 Web 应用程序,但遇到了一个问题。有一个登录用户的身份验证服务。我正在使用凭据向服务器发送请求并等待响应。问题是我尝试从登录组件导航到主组件在响应的订阅中

  login(formValues) {
    this.auth.logInUser(formValues.username, formValues.password)
    .subscribe(response =>{
      if(!response){
        this.invalidLogin=true;
      } else {
        this.router.navigate(['stream']);
      }
    })
  }

但是每个其他组件都有一个 canActivateGuard 来检查当前用户是否已登录(我正在等待来自服务器的数据)。

export const appRoutes: Routes = [
    {path: 'login', resolve: LiveStreamResolver, component: LoginComponent},
    {path: 'reports', component: ReportsComponent, resolve: LiveStreamResolver, canActivate: [AuthGuardService]},
    {path: 'calendar', component: CalendarComponent, resolve: LiveStreamResolver, canActivate: [AuthGuardService]},
    {path: 'stream', component: LiveStreamComponent},
    {path: '', redirectTo: 'login', pathMatch: 'full'}
];

constructor(public auth: AuthenticationService) { }

  canActivate(): boolean {
    return !!this.auth.currUser;
  }

在 canActivate 检查完成之前有没有办法解决?还有其他解决方案吗?
欢迎任何其他有关如何保护组件的建议:D

4

2 回答 2

1

我遇到了同样的问题,这就是我解决它的方法。

您可以Observable<boolean>从 canActivate 方法返回。尝试返回 Observable 而不是纯布尔值。

另外,另一种选择是,您可以返回承诺。

看看CanActivate

这是代码示例:

身份验证服务

    @Injectable()
    export class AuthenticationService {

        private isAuthenticatedSubject = new ReplaySubject<boolean>(0);
        public isAuthenticated = this.isAuthenticatedSubject.asObservable();

    constructor() { }

    /* Call this method once user successfully logged in. It will update the isAuthenticatedSubject*/
    setAuth() {
       this.isAuthenticatedSubject.next(true);
     }

   }

AuthgaurdService

@Injectable()
export class AuthgaurdService implements CanActivate {

    constructor(
        private router: Router,
        private authService: AuthenticationService) { }

    canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> {
        // this will return Observable<boolean>
        return this.authService.isAuthenticated.pipe(take(1));
    }
}
于 2018-07-31T01:51:32.403 回答
0

您可以使用 obervable ,这是一个示例:

constructor(private authService: AuthService, private router: Router) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    if (this.authService.isLoggedIn()) {
        return true;
    }
    this.router.navigate(['/login']);
    return false;
}
于 2018-07-31T03:17:51.710 回答