[英]RxJs/Angular2 map function on http response not called
Ok, there must be something I don't understand regarding the map()
function. 好的,关于
map()
函数肯定有些不明白的地方。 I'd expect that in both cases of the subscription the term mapped is written to the console. 我希望在两种订阅情况下, 映射的术语都会写入控制台。 However, it is not if the http response has a status code of 4xx.
但是,不是http响应的状态码为4xx。
http.get("http://my.domain/rest/path").map(
data => {
console.log("mapped");
return data;
}
).subscribe(
data => {
console.log("good");
},
error => {
console.log("bad");
}
);
Any hints here? 这里有什么提示吗?
map
function only proceeds 'good' data and not error. map
函数仅处理“良好”数据,不会出错。 In real case, I'd expect different body data for Ok
cases (real data) and Bad Request
cases (error messages) too. 在实际情况下,我希望
Ok
情况(实际数据)和Bad Request
情况(错误消息)的正文数据也不同。 To catch and handle error in http.get
function, use catch
: 要捕获并处理
http.get
函数中的错误,请使用catch
:
let obs = http.get("http://my.domain/rest/path").map(
data => {
console.log("mapped");
return data;
}
).catch(err => console.log(err));
obs.subscribe(...);
The Angular 2 Http
client treats responses with 4xx
and 5xx
status codes as errors . Angular 2
Http
客户端将状态码为 4xx
和5xx
响应视为错误 。 So the map
operator does not receive an emitted response. 因此,
map
操作员不会收到发出的响应。
Note that if an error is thrown due to the response's status code, the error will contain status
and statusText
properties: 请注意,如果由于响应的状态码而引发错误,则该错误将包含
status
和statusText
属性:
http.get("http://my.domain/rest/path").map(
data => {
console.log("mapped");
return data;
}
).subscribe(
data => {
console.log("good");
},
error => {
if (error.status) {
console.log("somewhat bad: " + error.status);
} else {
console.log("really bad");
}
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.