我正在尝试从一个服务调用map
,但得到一个错误。看看subscribe is not defined in angular 2?,它说为了订阅,我们需要从运算符内部返回。我也有返回语句。
下面是我的代码:
checkLogin(): Observable<boolean> {
return this.service
.getData()
.map(
(response) => {
this.data = response;
this.checkservice = true;
return true;
},
(error) => {
// debugger;
this.router.navigate(["newpage"]);
console.log(error);
return false;
}
)
.catch((e) => {
return e;
});
}
错误日志:
TypeError:在需要流的位置提供了无效的对象。您可以提供可观察、可承诺、可数组或可迭代的
发布于 2018-07-23 16:18:23
在我的例子中,错误只发生在e2e测试期间。它是由我AuthenticationInterceptor中的throwError
引起的。
我从错误的来源导入了它,因为我使用了WebStorm的导入功能。我使用的是RxJS 6.2。
错误:
import { throwError } from 'rxjs/internal/observable/throwError';
正确:
import { throwError } from 'rxjs';
截取程序的完整代码如下:
import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const reqWithCredentials = req.clone({withCredentials: true});
return next.handle(reqWithCredentials)
.pipe(
catchError(error => {
if (error.status === 401 || error.status === 403) {
// handle error
}
return throwError(error);
})
);
}
}
发布于 2017-04-22 02:11:46
在您的示例代码中,您让map
操作符接收两个回调,而实际上它应该只接收一个。您可以将错误处理代码移到catch回调中。
checkLogin():Observable<boolean>{
return this.service.getData()
.map(response => {
this.data = response;
this.checkservice=true;
return true;
})
.catch(error => {
this.router.navigate(['newpage']);
console.log(error);
return Observable.throw(error);
})
}
您还需要导入catch
和throw
操作符。
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
编辑:请注意,通过在捕获处理程序中返回Observable.throw
,您实际上不会捕获错误-它仍然会浮出控制台。
发布于 2018-02-06 07:00:45
如果您的函数期望返回一个布尔值,只需执行以下操作:
import { of, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
checkLogin(): Observable<boolean> {
return this.service.getData()
.pipe(
map(response => {
this.data = response;
this.checkservice = true;
return true;
}),
catchError(error => {
this.router.navigate(['newpage']);
console.log(error);
return of(false);
})
)}
https://stackoverflow.com/questions/43549223
复制相似问题