Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular APP_INITLIZER中的SwitchMap正在无限重复_Angular_Rxjs - Fatal编程技术网

Angular APP_INITLIZER中的SwitchMap正在无限重复

Angular APP_INITLIZER中的SwitchMap正在无限重复,angular,rxjs,Angular,Rxjs,我有一个脚本来验证我希望在应用程序初始化期间关闭的用户,因此我在app.module中提供了一个app\u初始值设定项。它发出一个HTTP调用,该调用通过两个开关映射运行,然后转换为承诺。HTTP调用工作,然后第一个switchMap启动一次,然后第二个switchMap无限启动并锁定应用程序。我不知道发生了什么,也不知道如何调试它。它在某种程度上起了作用,我不确定是什么变化打破了它 下面是返回到应用程序初始化器的方法: validateUser() { let jwt = this.g

我有一个脚本来验证我希望在应用程序初始化期间关闭的用户,因此我在
app.module
中提供了一个
app\u初始值设定项。它发出一个HTTP调用,该调用通过两个
开关映射运行,然后转换为承诺。HTTP调用工作,然后第一个switchMap启动一次,然后第二个switchMap无限启动并锁定应用程序。我不知道发生了什么,也不知道如何调试它。它在某种程度上起了作用,我不确定是什么变化打破了它

下面是返回到
应用程序初始化器的方法:

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);
}
validateUser(){
设jwt=this.getJWT();
if(jwt&&jwt.长度){
返回这个.api
.get('/users/validateToken',{token:jwt})
.烟斗(
开关映射(响应=>{
if(response.data.tokenValid){
this.setUser()
返回此.currentUser$.asObservable()
}否则{
返回Observieof(false);
}
}),
开关映射(currentUser=>{
如果(当前用户){
currentUser.getEvents();
此.setCurrentUser(当前用户);
}否则{
这是我的。注销()
}
返回observeof(true);
})
)
.toPromise();
}
返回承诺。解决(真实);
}

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

您在第一个开关映射中返回
this.currentUser$.asObservable()

然后从第二个开关映射更新当前用户
this.setCurrentUser(currentUser)

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

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


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

谢谢!我甚至不认为它能产生一个反馈回路…我以为开关图是线性的。是的,我知道我的代码需要很多改进(这是一种方法,你会对整个结构大喊大叫),只是没有人能给我建议,呵呵。