我在分析angular服务内部的JSON对象时遇到问题

6tdlim6h  于 2023-05-19  发布在  Angular
关注(0)|答案(2)|浏览(112)

我是新来的!我正在尝试解析一个Angular 服务中的响应

this.httpClient.get(this.url+formula).subscribe(response => {
      this.response = response
    });

response应该是这样的:

Object { code: 200, formula: "2", result: 2, status: "Success" }

我得到一个错误,当我特灵得到的状态,结果或代码:代码不工作

error TS2339: Property 'code' does not exist on type 'Object'.

我将非常感谢你的帮助

dz6r00yl

dz6r00yl1#

这里的问题是,typescript不能推断出您从请求中获得的是哪种对象,因此使用点表示法myObject.someProperty是行不通的,因为typescript不能识别someProperty。你需要显式地让typescript知道你得到的对象的类型,类似于这样:

this.httpClient.get<MyResponseType>(this.url+formula).subscribe(
    // Here typescript already knows the type of the response
    response => console.log(response.code) // works fine
)

或者,您可以尝试使用括号表示法访问属性:

this.httpClient.get(this.url+formula).subscribe(
    response => console.log(response['code']) // also works but doesnt provide autocomplete
)
8yparm6h

8yparm6h2#

我相信你必须明确地告诉Angular HttpClient,当你发出http请求时,你想访问整个响应(而不仅仅是主体)。您可以尝试以下操作:

this.httpClient.get<any>(this.url+formula, { observe: 'response' }).subscribe((response: HttpResponse<any>) => {
  this.response = response;
  console.log(response.code);
});

请注意,您可以将更改为更合适的类型,即此端点应在响应体中返回的对象的类型。

相关问题