【问题标题】:Angular - Resolving Observable data before canActivateAngular - 在 canActivate 之前解析 Observable 数据
【发布时间】:2019-01-07 07:16:34
【问题描述】:


我正在使用 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

【问题讨论】:

  • 请检查更新后的答案:)

标签: angular authentication observable resolve canactivate


【解决方案1】:

我遇到了同样的问题,下面是我的解决方法。

您可以从 canActivate 方法返回Observable<boolean>。尝试返回 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));
    }
}

【讨论】:

  • 如果 observable 失败或用户未通过身份验证,您如何控制?页面挂起/什么都不做
【解决方案2】:

你可以使用 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 2017-01-04
    • 2017-11-25
    • 1970-01-01
    • 2023-03-27
    • 2018-06-05
    • 1970-01-01
    • 2014-08-09
    相关资源
    最近更新 更多