Ok, there must be something I don't understand regarding the map()
function. 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.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. In real case, I'd expect different body data for Ok
cases (real data) and Bad Request
cases (error messages) too. To catch and handle error in http.get
function, use 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 . So the map
operator does not receive an emitted response.
Note that if an error is thrown due to the response's status code, the error will contain status
and statusText
properties:
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");
}
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.