catch对于http.get Angular2不起作用 [英] catch is not working for http.get Angular2
本文介绍了catch对于http.get Angular2不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Http服务进行ajax调用,该方法工作正常.
I am trying to make an ajax call with Http service, which is working fine.
现在,我想处理失败案例.如果我们收到404或其他任何错误的示例.
Now I would like to handle failure cases. Example if we get 404 or any other errors.
我正在使用以下代码.
I am using the following code.
import {Component,Inject} from '@angular/core';
import {Http, Response,HTTP_PROVIDERS} from '@angular/http';
import {DoService} from './service';
import 'rxjs/Rx';
import 'rxjs/add/operator/catch';
@Component({
selector: 'comp-one',
template: `<h2>My First Angular 2 App</h2>{{data}}
<input type="button" (click)="doSomething()" value="Do Http"/>`
})
export class ComponentOne {
constructor(public _http:Http){
console.log("It is from ComponentOne constructor..");
this._http = _http;
}
data:Object;
doSomething(){
console.log("It is from doSomething ComponentOne");
let temp:any = this._http.get('people.json')//people.json is not exist, intendedly maing any error
.map(res => res.json())
.catch((err:any)=>{ console.log("Something is wrong..")});// If i keep this line i am getting errors like "Argument of type '(err:any) => void' is not assignable to parameter of type '(err: any, caught: Observable<any>) => Observable<{}>"
temp.subscribe(
(res:any)=> {this.data = res._body; console.log(res)},
(error:any)=>{ console.log("It isf from error..")},//It is not even getting called this block
() => console.log('thire,,,ddjfladjfljasdlfj'));//In one of the forum they suggested to use this 3rd perameter, this is also not working for me.
}
}
推荐答案
您需要从catch块返回observable,因为这是此签名.因此,尝试
You need to return observable from the catch block as this is the signature of this. So try
return Observable.throw(new Error(error.status));
这是代码段
import {Observable} from 'rxjs/Rx';
...
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if (res.status === 201) {
return [{ status: res.status, json: res }]
}
else if (res.status === 200) {
return [{ status: res.status, json: res }]
}
}
}).catch((error: any) => {
if (error.status === 500) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 400) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 409) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 406) {
return Observable.throw(new Error(error.status));
}
});
}
另请参见
这篇关于catch对于http.get Angular2不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文