管道 HTTP 调用时 RxJS SwitchMap 错误
RxJS SwitchMap Error when Piping HTTP Call
我试图在进行 HTTP 调用后使用 switchMap 运算符在我的 angular 服务中执行一些操作,但是它每次都抛出错误并且根本不执行 http 调用,并且给出非常模糊的错误响应
我有一个像这样调用我的服务的组件:
this.authService.login$(userRegistration).subscribe(result => {
// Doing things here
});
authservice 调用如下所示:
login$(userRegistration: UserRegistrationRequest): Observable<AuthResult> {
return this.http.post<AuthResult>(url, userRegistration)
.pipe(
switchMap(result => {
if(result.errors || result.errors.length !== 0) {
throw(result.errors);
}
// do things and then
return of(result);
}),
error => {
throw(error);
}
);
}
这会导致 http post 永远不会被触发,并立即出现上图错误。如果我删除 switchMap,return 只是服务中的可观察对象,然后在组件中订阅它,调用就会成功。
这里有我遗漏的东西吗?我对 rxjs 比较陌生,所以我不确定我是否误解了什么,但我们将不胜感激。
编辑:
我还能够将 switchMap 移动到组件中,做我需要的,然后在最后调用订阅,它工作正常。这是总体上更好的做法吗?
error()
不是 RxJS 中包含在 pipe()
中的有效运算符,相反你想使用 catchError()
来处理特定的错误情况。但是看看你的例子,你不需要使用它,因为 Angular 会捕获从你的 HTTP observable 抛出的任何错误。
此外,您不需要使用 switchMap,因为您不依赖于另一个可观察对象。只需使用 map()
运算符和 return result
而不是 of(result)
.
login$(userRegistration: UserRegistrationRequest): Observable<AuthResult> {
return this.http.post<AuthResult>(url, userRegistration)
.pipe(
map(result => {
if(result.errors || result.errors.length !== 0) {
throw(result.errors);
}
// do things and then
return result;
})
);
}
我试图在进行 HTTP 调用后使用 switchMap 运算符在我的 angular 服务中执行一些操作,但是它每次都抛出错误并且根本不执行 http 调用,并且给出非常模糊的错误响应
我有一个像这样调用我的服务的组件:
this.authService.login$(userRegistration).subscribe(result => {
// Doing things here
});
authservice 调用如下所示:
login$(userRegistration: UserRegistrationRequest): Observable<AuthResult> {
return this.http.post<AuthResult>(url, userRegistration)
.pipe(
switchMap(result => {
if(result.errors || result.errors.length !== 0) {
throw(result.errors);
}
// do things and then
return of(result);
}),
error => {
throw(error);
}
);
}
这会导致 http post 永远不会被触发,并立即出现上图错误。如果我删除 switchMap,return 只是服务中的可观察对象,然后在组件中订阅它,调用就会成功。
这里有我遗漏的东西吗?我对 rxjs 比较陌生,所以我不确定我是否误解了什么,但我们将不胜感激。
编辑: 我还能够将 switchMap 移动到组件中,做我需要的,然后在最后调用订阅,它工作正常。这是总体上更好的做法吗?
error()
不是 RxJS 中包含在 pipe()
中的有效运算符,相反你想使用 catchError()
来处理特定的错误情况。但是看看你的例子,你不需要使用它,因为 Angular 会捕获从你的 HTTP observable 抛出的任何错误。
此外,您不需要使用 switchMap,因为您不依赖于另一个可观察对象。只需使用 map()
运算符和 return result
而不是 of(result)
.
login$(userRegistration: UserRegistrationRequest): Observable<AuthResult> {
return this.http.post<AuthResult>(url, userRegistration)
.pipe(
map(result => {
if(result.errors || result.errors.length !== 0) {
throw(result.errors);
}
// do things and then
return result;
})
);
}