本文介绍了Rxjs catchError在管道后订阅时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个使用API的可观察对象
I have created an observable to consume an API
可观察:-
return this.http.post('/api/ApplicationUser/Login', loginDetails, httpOptions).pipe(
map((result: any) => {
localStorage.setItem('jwtToken', result.jwtToken);
localStorage.setItem('refreshToken', result.refreshToken.value)
localStorage.setItem('UserName', result.userName);
return result;
}),
catchError((err: any) => {
//this.userLogout()
console.log('refresh error')
return throwError(err);
})
);
}
使用Iam激活以下代码时,根据我的情况,以上代码可以正常工作,结果也可以抛出错误:-
Above code is working fine by results or throwing errors according to my situations when Iam activating with below code:-
this.loginService.getNewRefreshToken().subscribe(
(res => { console.log(res) }),
(err => {
this.loginService.userLogout()
console.log(err)
}),
() => { console.log('subscription completed')},
);
但是我的问题是,当我用下面的代码激活它时,catchError无法正常工作,但结果很好.为什么catchError在以下情况下不起作用?
But my problem is when Iam activating it with below code its catchError not working but results are fine.Why catchError is not working in below case?
return this.loginService.getNewRefreshToken().pipe(
map((res: any) => {
console.log(res);
}),
catchError((err: any) => {
console.log(err);
return throwError(err);
})
).subscribe(
(res => {
console.log(res)
}),
(err => {
console.log(err)
})
)
推荐答案
您的getNewRefreshToken
函数会吃掉该异常,因此不会传播到上游侦听器.
Your getNewRefreshToken
function eats the exception hence it does not get propagated to upstream listeners.
尝试 throwError
getNewRefreshToken(): Observable<any> {
var loginDetails: LoginDetails = {
email: localStorage.getItem('UserName'),
grantType: 'refreshToken',
password: '',
refreshToken: localStorage.getItem('refreshToken')
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
}),
};
return this.http.post('/api/ApplicationUser/Login', loginDetails, httpOptions).pipe(
map((result: LoginResponse) => {
localStorage.setItem('jwtToken', result.jwtToken);
localStorage.setItem('refreshToken', result.refreshToken.value)
localStorage.setItem('UserName', result.userName);
return result;
}),
catchError((err: any) => {
this.userLogout()
console.log('refresh error')
return throwError(err); //<-- insert this
})
);
}
示例查看结果控制台.
这篇关于Rxjs catchError在管道后订阅时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!