gpt4 book ai didi

http - 如何从 http.request() 中正确捕获异常?

转载 作者:太空狗 更新时间:2023-10-29 16:45:03 47 4
gpt4 key购买 nike

我的部分代码:

import {Injectable} from 'angular2/core';
import {Http, Headers, Request, Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class myClass {

constructor(protected http: Http) {}

public myMethod() {
let request = new Request({
method: "GET",
url: "http://my_url"
});

return this.http.request(request)
.map(res => res.json())
.catch(this.handleError); // Trouble line.
// Without this line code works perfectly.
}

public handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}

}

myMethod() 在浏览器控制台产生异常:

ORIGINAL EXCEPTION: TypeError: this.http.request(...).map(...).catch is not a function

最佳答案

也许你可以尝试在导入中添加这个:

import 'rxjs/add/operator/catch';

您还可以:

return this.http.request(request)
.map(res => res.json())
.subscribe(
data => console.log(data),
err => console.log(err),
() => console.log('yay')
);

根据评论:

EXCEPTION: TypeError: Observable_1.Observable.throw is not a function

同样,为此,您可以使用:

import 'rxjs/add/observable/throw';

关于http - 如何从 http.request() 中正确捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35326689/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com