gpt4 book ai didi

javascript - Observable 方法在 catch block 后返回 null

转载 作者:行者123 更新时间:2023-11-30 11:31:14 25 4
gpt4 key购买 nike

鉴于此方法:为什么登录状态是 null 而不是 false

// this method is called below, I am attempting to return only true or false.
isLoggedIn(): Observable<boolean> {
return this
.loadToken()
.catch(e => {
this.logger.info(e); // this is being logged...
this.token = null;
return Observable.of(false); // and I specifically return false.
})
.map(_ => this.token && this.token.access_token.length > 0);

正在从这里调用它

return this.authService.isLoggedIn().map(_ => {
this.logger.info(`authorisation guard :: login status ${_}`);
if (_)
return true;
this.router.navigate(["login"]);
return Observable.of(false);
}).catch(_ => {
this.logger.info(`authorisation guard :: login error ${_}`);
this.router.navigate(["login"]);
return Observable.of(false);
});

记录了以下获取:

2017-09-09T06:55:46Z [INFO] authorisation guard :: login status null

我很期待

2017-09-09T06:55:46Z [INFO] authorisation guard :: login status false

最佳答案

您已将 catch 放在 map 之前:

isLoggedIn(): Observable<boolean> {
return this
.loadToken()
.catch(e => {
this.logger.info(e);
this.token = null;
return Observable.of(false);
})
.map(_ => this.token && this.token.access_token.length > 0);

这意味着当 loadToken 发生错误时,它将被 catch 捕获,并且 observable 链将使用从 catch 返回的 observable 恢复 运算符:Observable.of(false)

因此,false 将被传递给 map,在那里它会被忽略并返回 this.token 的值 - 如它将为 null 并且逻辑表达式中的第一个测试将失败。

您很可能希望将 catch 放在 map 之后。

关于javascript - Observable<Boolean> 方法在 catch block 后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46128072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com