角度6,订阅Observables无效

时间:2019-04-21 22:04:29

标签: angular

我有一个Angular 6应用程序,在该应用程序中我似乎无法正确订阅可观察对象,以便确定用户是否已登录。

在我的auth.guard中,我有以下内容,您可以看到在我的函数从不访问的位置添加了注释的地方:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  return this.authenticationService.isLoggedIn().pipe(map(loggedIn => {
    // I never get here
    if (!loggedIn) {
      window.location.href = environment.wolfUrl + 'account/login';;

    }
    return loggedIn;
  }));
}

这是我的isLoggedIn()函数:

isLoggedIn(): Observable<boolean> {
   this.userService.getUserWithRolesByUserName('test')
        .pipe(first())
        .subscribe(
            result => {
                this.currentUser = result;
                if (this.currentUser.fullName != 'test name') {
                    subject.next(false);
                } else {
                    subject.next(true);
                }

            },
            () => { 
                subject.next(false);
            });
    return subject.asObservable();
}

我在做什么错?

修改

这是我的函数getUserWithRolesByUserName

public getUserWithRolesByUserName(userName): Observable<User> {
    return this.http.get<User>(this.baseUrl + '/getUserWithRolesByUserName?userName=' + userName);
}

3 个答案:

答案 0 :(得分:0)

我认为getUserWithRolesByUserName是同步的,因此,您在订阅之前发出要接受主题的事件。 尝试

isLoggedIn(): Observable<boolean> {
   return this.userService.getUserWithRolesByUserName('test')
        .pipe(
          first(),
          map(result => {
           this.currentUser = result;
           return this.currentUser.fullName == 'test name';
          }),
          catchError(() => of(false)),
          tap(value => this.subject.next(value)),
        );
}

答案 1 :(得分:0)

在“ canActivate”方法中,您需要订阅“ isLoggedIn”方法返回的可观察对象。例如

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  return this.authenticationService.isLoggedIn().pipe(map(loggedIn => {
    // I never get here
    if (!loggedIn) {
      window.location.href = environment.wolfUrl + 'account/login';;

    }
    return loggedIn;
  }))
  .subscribe(); // !!!
}

答案 2 :(得分:0)

只需将一个可观察的对象返回给authguard,而不是订阅,那么您就可以摆脱subject,如果您在其他任何地方都不需要它,我认为这是多余的。因此,将isLoggedIn()修改为:

isLoggedIn(): Observable<boolean> {
  return this.userService.getUserWithRolesByUserName('test')
    .pipe(
      first(),
      map((result) => {
        this.currentUser = result;
        if (this.currentUser.fullName != 'test name') {
           return false;
        }
        return true;
      }),
      catchError(() => of(false)),
    )
}
相关问题