Angular 如何在typescript中打开http post响应中的对象?
如何打开从HTTP POST请求接收的对象 这是我的密码:Angular 如何在typescript中打开http post响应中的对象?,angular,typescript,http,post,google-cloud-functions,Angular,Typescript,Http,Post,Google Cloud Functions,如何打开从HTTP POST请求接收的对象 这是我的密码: this.http.post(url, user, httpOptions).subscribe(result => { console.log(result.status); }); 我在console.log()上得到了错误 如何打开结果变量/响应对象,以便读取typescript中的各个值 如果我使用console.log(result),我可以看到所有的值 如果希望在httpOptions中包含整个HttpRespo
this.http.post(url, user, httpOptions).subscribe(result => {
console.log(result.status);
});
我在console.log()上得到了错误
如何打开结果变量/响应对象,以便读取typescript中的各个值
如果我使用console.log(result),我可以看到所有的值 如果希望在
httpOptions
中包含整个HttpResponse
,则需要指定observe:'response'
。默认行为是observed:'body'
,它返回响应主体的可观察的
。这也被描述
我创建了一个示例来演示这应该如何工作(请参见控制台输出)
但是,您得到的错误是一个TypeScript错误。响应被推断为类型对象
——它显然没有任何状态
属性。通常,类型应该是正确的。您可以通过将响应键入any
来绕过这个问题
this.http.post(url, user, httpOptions).subscribe(result => {
console.log((result as any).status); // Take the type information away for this statement
});
老实说,我不建议这样做。您应该首先调查为什么将响应推断为
Object
。在运行console.log(result)后发布您得到的结果“如果我是console.log(result),我可以看到所有的值。”我想这与httpoptions无关,这很奇怪。你所做的似乎是正确的,正如这里所说的@robert补充了关于实际问题的更多信息。我仍然不知道为什么这里的类型是错误的。。。
this.http.post(url, user, {
...httpOptions, // or specifiy it inside httpOptions directly
observe: 'response'
}).subscribe(result => {
console.log(result.status);
});
this.http.post(url, user, httpOptions).subscribe(result => {
console.log((result as any).status); // Take the type information away for this statement
});