[英]How to unwrap object in http post response in typescript?
How do I unwrap an object received from an HTTP POST request? 如何解开从HTTP POST请求收到的对象?
Here is my code: 这是我的代码:
this.http.post(url, user, httpOptions).subscribe(result => {
console.log(result.status);
});
I am getting the error on the console.log() 我在console.log()上收到错误
Property 'status' does not exist on type 'Object'.
How do I unwrap the result variable/response object so I can read the individual values in typescript? 如何解开结果变量/响应对象,以便可以读取打字稿中的各个值?
If I console.log(result), I can see all the values. 如果我console.log(result),我可以看到所有值。
You need to specify observe: 'response'
if you want the whole HttpResponse
in your httpOptions
. 如果要在httpOptions
使用整个HttpResponse
,则需要指定observe: 'response'
。 The default behaviour is observe: 'body'
, which returns an Observable
of the response body. 默认行为是observe: 'body'
,它返回响应主体的Observable
。 This is also described here. 这也在此处描述。
I created a StackBlitz demonstrating how this should work (see console output). 我创建了一个StackBlitz,演示了它如何工作(请参阅控制台输出)。
this.http.post(url, user, {
...httpOptions, // or specifiy it inside httpOptions directly
observe: 'response'
}).subscribe(result => {
console.log(result.status);
});
The error you are getting is a TypeScript error though. 您得到的错误是TypeScript错误。 The response is inferred as type Object
- which obviously doesn't have any status
property. 响应被推断为Object
类型-显然没有任何status
属性。 Usually, the types should be correct. 通常,类型应该正确。 You could go around the issue by typecasting the response to any
. 您可以通过将响应类型转换为any
来解决该问题。
this.http.post(url, user, httpOptions).subscribe(result => {
console.log((result as any).status); // Take the type information away for this statement
});
To be honest, I wouldn't suggest doing that though. 老实说,我不建议这样做。 You should investigate why the response is inferred as Object
in the first place. 您应该首先调查为什么将响应推断为Object
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.