【问题标题】:How do I access a property of the “response” of an API call from my Angular operation?如何从我的 Angular 操作访问 API 调用的“响应”属性?
【发布时间】:2020-04-11 19:16:48
【问题描述】:

我有一个用 NODE.JS 制作的 API,它带来一个对象作为其响应,我在下面发布了一张图片。

这是我在 users.component.ts 文件中的打字稿代码。

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})

export class UsersComponent {
  users: any[];
  constructor(http: HttpClient) {
    http.get('url').subscribe(response => {
      console.log(response.recordset);
      this.users=response.recordset;
    });
  }
}

这是我收到的错误消息:

src/app/users/users.component.ts:14:28 - 错误 TS2339:“对象”类型上不存在属性“记录集”。

14 console.log(response.recordset);

src/app/users/users.component.ts:15:27 - 错误 TS2339:“对象”类型上不存在属性“记录集”。

15 this.users=response.recordset;

如何访问这个“记录集”属性并将其添加到用户数组中?

【问题讨论】:

  • 试试http.get<any>(url).subscribe(response => {...}

标签: angular angular-httpclient


【解决方案1】:

如果您不知道返回响应的响应类型,您可以通过添加 any 来避免错误,这将为您解决问题。

但是最好的做法是有响应的类型,

  http.get('url').subscribe((response : any) => {

【讨论】:

    猜你喜欢
    • 2020-11-07
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多