[英]Property 'catch' does not exist on type 'Observable<any>'
On the Angular 2 documentation page for using the Http service, there is an example.在使用 Http 服务的 Angular 2 文档页面上,有一个示例。
getHeroes (): Observable<Stuff[]> {
return this.http.get(this.url)
.map(this.extractData)
.catch(this.handleError);
}
I cloned the angular2-webpack-starter project and added the above code myself.我克隆了angular2-webpack-starter项目并自己添加了上面的代码。
I imported Observable
using我使用导入
Observable
import {Observable} from 'rxjs/Observable';
I'm assuming the properties Observable
are imported as well ( .map
works).我假设
Observable
的属性也被导入( .map
有效)。 Looked at the changelog for rxjs.beta-6 and nothing is mentioned about catch
.查看 rxjs.beta-6 的更新日志,没有提到
catch
。
Warning : This solution is deprecated since Angular 5.5, please refer to Trent's answer below警告:此解决方案自 Angular 5.5 起已弃用,请参考下面 Trent 的回答
===================== ======================
Yes, you need to import the operator:是的,您需要导入运算符:
import 'rxjs/add/operator/catch';
Or import Observable
this way:或者以这种方式导入
Observable
:
import {Observable} from 'rxjs/Rx';
But in this case, you import all operators.但在这种情况下,您导入所有运算符。
See this question for more details:有关更多详细信息,请参阅此问题:
With RxJS 5.5+, the catch
operator is now deprecated.在 RxJS 5.5+ 中,现在不推荐使用
catch
运算符。 You should now use the catchError
operator in conjunction with pipe
.您现在应该将
catchError
运算符与pipe
结合使用。
RxJS v5.5.2 is the default dependency version for Angular 5.
RxJS v5.5.2 是 Angular 5 的默认依赖版本。
For each RxJS Operator you import, including catchError
you should now import from 'rxjs/operators' and use the pipe operator.对于您导入的每个 RxJS 运算符,包括
catchError
您现在应该从 'rxjs/operators' 导入并使用管道运算符。
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
...
export class ExampleClass {
constructor(private http: HttpClient) {
this.http.request(method, url, options).pipe(
catchError((err: HttpErrorResponse) => {
...
}
)
}
...
}
Notice here that catch
is replaced with catchError
and the pipe
operator is used to compose the operators in similar manner to what you're used to with dot-chaining.请注意,
catch
被catchError
替换, pipe
运算符用于以与您习惯于使用点链接的方式类似的方式组合运算符。
See the rxjs documentation on pipable (previously known as lettable ) operators for more info.查看该rxjs文档pipable (以前称为可出租获取更多信息)运营商。
In angular 8:在角度 8 中:
//for catch:
import { catchError } from 'rxjs/operators';
//for throw:
import { Observable, throwError } from 'rxjs';
//and code should be written like this.
getEmployees(): Observable<IEmployee[]> {
return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
}
erroHandler(error: HttpErrorResponse) {
return throwError(error.message || 'server Error');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.