代码之家  ›  专栏  ›  技术社区  ›  Rohit

应用程序初始化器中的switchmap无限重复

  •  0
  • Rohit  · 技术社区  · 8 年前

    我有一个脚本来验证我想在应用程序初始化期间关闭的用户,因此我提供了一个 APP_INITIALIZER 在里面 app.module 是的。它发出一个http调用,它通过两个 switchMaps 然后变成承诺。http调用起作用,然后第一个switchmap激发一次,然后第二个switchmap无限激发并锁定应用程序。我不知道发生了什么,也不知道如何调试。它在某个时候起作用了,我不确定是什么改变打破了它。

    下面是返回到 APP_INITLIZER 以下内容:

    validateUser() {
        let jwt = this.getJWT();
        if (jwt && jwt.length) {
            return this.api
                .get<{ data: { tokenValid: boolean } }>('/users/validateToken', { token: jwt })
                .pipe(
                    switchMap(response => {
                        if (response.data.tokenValid) {
                            this.setUser()
                            return this.currentUser$.asObservable()
                        } else {
                            return ObservableOf(false);
                        }
                    }),
                    switchMap(currentUser => {
                        if (currentUser) {
                            currentUser.getEvents();
                            this.setCurrentUser(currentUser);
                        } else {
                            this.logout()
                        }
    
                        return ObservableOf(true);
                    })
                )
                .toPromise();
        }
    
        return Promise.resolve(true);
    }
    

    currentUser$ 如果重要的话,是一个行为主体。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Xinan    8 年前

    你回来了 this.currentUser$.asObservable() 在第一个切换图中。

    然后从第二个switchmap更新当前用户 this.setCurrentUser(currentUser) 是的。

    这将导致第一个switchmap内部的observate发出一个新值。所以它是无限期的。

    虽然我认为您的代码可以改进,但最简单的解决方案是更改一行代码。

    this.currentUser$.asObservable().pipe(first())