首页 > 解决方案 > 创建一个订阅,一旦捕获到一​​个有效的 authState,就会停止“轮询”

问题描述

是否可以创建一个尝试反复获取用户身份验证状态的订阅,直到user != null,一旦出现这种情况,它就会停止:

  ngOnInit() {
    this.isMobile = this.breakpointObserver.observe([Breakpoints.Handset]);
    this.authSubscription = this.afAuth.authState.subscribe(user => {
      if(user) {
        localStorage.setItem('uid', user.uid);
        this.store.dispatch(userActions.getData());
      }
    })
  }

控制台输出如下导致浏览器崩溃:

在此处输入图像描述

我的操作如下:

  @Effect()
  getData$ = this.actions$.pipe(
    ofType(UserActions.getData),
    switchMap(() => {
        return this.userService.getUserById(localStorage.getItem('uid')).pipe(
          map(
            (data: IUser) => UserActions.dataReceived({ payload: UserService.parseData(data) })
          )
        );
      }
    )
  );

标签: angulartypescriptngrx

解决方案


您可以使用takeUntil()运算符 和的组合interval()

我更喜欢这种解决方案,因为您不会一个接一个地触发请求 1,您需要在两者之间留出一些时间。


推荐阅读