【问题标题】:Angular async pipe is not refreshing when observable changed可观察值更改时,角度异步管道不刷新
【发布时间】:2019-05-28 15:12:58
【问题描述】:

我有一个 Angular 应用程序。

  • 在应用初始化时,我们应该显示重定向微调器(用户未登录)
  • 当用户登录后,我们应该显示内容

我做了如下: HTML:

<div *ngIf="(isLoggedIn$ | async); else loading">
    <!-- some other content -->
    <router-outlet></router-outlet>
</div>

<ng-template #loading>
    <app-spinner text="Redirecting..."></app-spinner>
</ng-template>

TS:

isLoggedIn$: Observable<boolean>;

constructor(private authService: AuthService) {}

ngOnInit() {
    this.isLoggedIn$ = this.authService.isLoggedIn();
}

它在应用程序初始化时运行良好。当用户登录时,我仍然看到重定向微调器。我必须刷新窗口才能看到路由器插座的内容。

我的临时解决方法是将&lt;router-outlet&gt; 放入&lt;ng-template #loading&gt;,例如:

<ng-template #loading>
    <app-spinner text="Redirecting..."></app-spinner>
    <router-outlet></router-outlet> <!-- HERE workaround -->
</ng-template>

但不想永久使用此解决方法,因为我想修复此 Observable 问题 - 正如我所提到的,即使 console.log() 说我已登录,它也不会刷新。

这是我的身份验证服务:

@Injectable({
    providedIn: 'root'
})
export class AuthService {

  manager: UserManager = new UserManager(environment.settings);

  constructor() {
  }

  getUser(): Observable<User> {
    return from(this.manager.getUser());
  }

  isLoggedIn(): Observable<boolean> {
    return this.getUser()
      .pipe(
        map(user => {
          return user != null && !user.expired;
        })
      );
  }

  startAuthentication(): Promise<void> {
    return this.manager.signinRedirect();
  }

  completeAuthentication(): Observable<User> {
    return from(this.manager.signinRedirectCallback());
  }

  async signOut() {
    await this.manager.signoutRedirect();
  }
}

当然,我也在使用CanActivate

【问题讨论】:

  • 能看到this.authService.isLoggedIn的代码吗?
  • 如何解决这个问题? app-spinner 还不转吗?
  • 不要有条件地删除&lt;router-outlet&gt;,因为路由器无法激活路由。这与 isLoggedIn$ observable 无关。
  • 如果您想控制路由,请使用路由器功能之一。例如 CanActivate。
  • 只是为了确定 - 是否 observable 发射?也许tapconsole.log 一起检查。

标签: angular asynchronous observable


【解决方案1】:

我的解决方案是将emitCompleted 方法添加到AuthService 并从AuthCallback 组件中调用它。

授权服务:

private isLoggedInState = new BehaviorSubject<boolean>(false);

isLoggedIn(): Observable<boolean> {
    return this.isLoggedInState.asObservable();
}

emitCompleted(user: User) {
    this.isLoggedInState.next(user != null && !user.expired);
}

AuthCallback 组件:

export class AuthCallbackComponent implements OnInit {

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

  ngOnInit() {
    this.authService.completeAuthentication()
      .subscribe((result => {
        this.authService.emitCompleted(result);
      })
    );
  }
}

【讨论】:

    猜你喜欢
    • 2018-08-06
    • 2019-09-22
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    相关资源
    最近更新 更多