【发布时间】:2016-12-30 11:47:34
【问题描述】:
Angular 2 的问题在 AngularJS 中不存在,我将错误消息作为带有后端 API 调用的字符串发送,以防出现错误,以错误状态 401 为例,现在的问题是我不能从 Angular2 http 响应消息中读取此消息,而我可以从 AngularJS 中做到这一点:
我尝试了以下代码,但没有任何帮助:
承诺:
this._http.post('/login',{email: 'email@example.com', password: '123'})
.toPromise()
.then((resp) => console.log(resp), (error) => console.log(error));
可观察:
this._http.post('/login',{email: 'email@example.com', password: '123'})
.subscribe(response =>console.log(response), (error) => console.log(error));
我从后端发送响应作为文本,对于 OK 或 Unauthorized,对于 OK,我发回 String token == UUID.randomUUID().toString();,对于错误,我发回类似 String error = " Invalid credentials "; 的消息,问题是 console.log 有效并且打印成功的文本(在这种情况下是令牌),但如果出现错误,它只会打印:Response with status: 200 for URL: null。
如果我将代码更改为JSON.stringify(error),我会得到如下信息:
{"_body":{},"status":401,"ok":false,"statusText":"Unauthorized","headers":{"null":["HTTP/1.1 401 Unauthorized"],"Access-Control-Allow-Headers":["Origin"," X-Requested-With"," Content-Type"," Accept"," Referer"," User-Agent"],"Access-Control-Allow-Met
hods":["POST"," GET"," PUT"," DELETE"," OPTIONS"],"Access-Control-Allow-Origin":["*"],"Allow":["*"],"Content-Length":["36"],"Content-Type":["text/plain; charset=utf-8"],"Date":["Tue"," 23 Aug 2016 14:53:25 GMT"]},"type":2,"url":null}
正如您所见,Object 内部甚至没有提到错误测试!
我尝试将后端的错误响应更改为返回 json,如下所示:
{
"message": "invalid email or password"
}
我可以在_body里面得到结果,我只能这样读:console.log(error._body.message)!但我觉得这种方式有问题,在这种情况下我不想以 json 的形式响应。
对于 angularjs (angular 1),打印响应非常简单,一切都很酷,而在 angular 2 中,这是一个真正的问题。
什么问题,以及如何在不对后端进行任何重构的情况下解决这个问题?
编辑:
我使用 Angular 2.0.0-rc.4 和 http 相同:`"@angular/http": "2.0.0-rc.4"
【问题讨论】:
标签: rest angular angular2-http