APP_INITLIZER中的SwitchMap无限重复

问题描述 投票:0回答:1

我有一个脚本来验证用户我想在app initlization期间关闭,所以我在APP_INITIALIZER中提供app.module。它进行HTTP调用,它通过两个switchMaps运行,然后转换为promise。 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$是一个行为主体。

angular rxjs
1个回答
0
投票

您在第一个SwitchMap中返回this.currentUser$.asObservable()

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

这将导致第一个SwitchMap内部的observable发出一个新值。所以它无限期地发展。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.