gpt4 book ai didi

angular - 可观察 map 功能未运行(Angular2,http)

转载 作者:太空狗 更新时间:2023-10-29 17:19:15 26 4
gpt4 key购买 nike

更新

问题似乎是 map 功能未在“失败”请求上运行。这意味着如果我正在与之交谈的 API 返回 422 Validation Failed 错误(或其他 4xx 错误)Angular 会将此视为失败并导致 Observer 运行订阅的错误回调,跳过进程中的map函数。

是否可以强制 Angular 将某些 4xx 错误视为成功请求,或者即使 Observable 返回错误也强制 map 函数运行?


我的 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;
});
}

代码执行正常,除了没有触发 map 函数。我没有收到任何错误,并尝试在使用和不使用 import 'rxjs/add/operator/map' 的情况下运行代码,结果相同。我还尝试了一个更简单的 map 函数 .map (res => res.json());

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

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

Request details

响应:

[{"field":"email","message":"Email or password incorrect."},{"field":"password","message":"Email or password incorrect."}]

我还针对完全成功的请求(状态代码:200)对其进行了测试, map 功能似乎工作正常。所以我猜它只会在返回成功响应时运行。有没有办法让它运行,或者指定它应该运行的附加状态代码?

最佳答案

如评论所述,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());
}

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

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

打印出来的内容是:

err = {
"code": 404,
"description": "The server has not found anything matching the request URI",
"reasonPhrase": "Not Found"
}

希望对你有帮助,蒂埃里

关于angular - 可观察 map 功能未运行(Angular2,http),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34855992/

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