可观察的Map函数未运行(Angular2,http)

Tam*_*Tam 7 observable rxjs angular2-http angular

更新

问题似乎是map函数不是在"失败"的请求上运行.这意味着如果我正在谈论的API返回422 Validation Failed错误(或其他4xx错误),Angular会将此视为失败并导致Observer运行订阅的错误回调,跳过该过程中的map函数.

是否有可能强制Angular将某些4xx错误视为成功请求,或强制映射函数即使在Observable返回错误时也能运行?


我在Angular2应用程序中运行以下代码:

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

...

public login (email : string, password : string) {
    return this.http.post(_endPoint + '/auth/login/', JSON.stringify({
        email: email,
        password: password
    }), {
        headers: new Headers({
            'Content-Type': 'application/json'
        })
    })
    .map (res => {
        let data = res.json();
        console.log(data);
        return data;
    });
}
Run Code Online (Sandbox Code Playgroud)

代码执行正常,但不触发map函数.我没有收到任何错误,并尝试使用和不import 'rxjs/add/operator/map'使用相同的结果运行代码.我也尝试过一个更简单的地图功能.map (res => res.json());.

在这两种情况下,我都希望.subscribe()函数中返回的结果是JSON响应,但我得到的是原始响应.

编辑:添加了请求数据和响应的屏幕截图

请求详情

响应:

[{"field":"email","message":"Email or password incorrect."},{"field":"password","message":"Email or password incorrect."}]
Run Code Online (Sandbox Code Playgroud)

我也在一个完全成功的请求(状态代码:200)上测试了它,地图功能似乎工作正常.所以我想它只会在返回成功的响应时运行.有没有办法让它无论如何运行,或者指定它应该运行的其他状态代码?

Thi*_*ier 7

正如与注释所讨论的那样,该map方法未被调用,因为响应包含422状态代码,即错误.因此直接调用catch方法.

如果您需要提取与错误相对应的JSON内容,您可以在服务中尝试类似的内容:

getCompanies() {
  return this.http.get('https://angular2.apispark.net/v1/companies1/', {
    headers: headers
  }).map(res => res.json()).catch(err => Observable.throw(err.json());
}
Run Code Online (Sandbox Code Playgroud)

现在,在调用服务的组件中,您将能够订阅.在您的情况下,将使用响应的JSON内容调用第二个参数:

service.getCompanies().subscribe(
  data => console.log('data = '+data),
  err => console.log('err = '+JSON.stringify(err, null, 2)), // <---
  () => console.log('complete')
);
Run Code Online (Sandbox Code Playgroud)

印刷内容如下:

err = {
  "code": 404,
  "description": "The server has not found anything matching the request URI",
  "reasonPhrase": "Not Found"
}
Run Code Online (Sandbox Code Playgroud)

希望它对你有帮助,蒂埃里