【问题标题】:How to create interface for object with a nested array如何使用嵌套数组为对象创建接口
【发布时间】:2021-06-04 14:22:31
【问题描述】:

我正在创建一个简单的 GET 请求,以列出来自 Angular / TypeScript 中的集成帐户的对象。以下是响应示例:

{
  "value": [
    {
      "properties": {
        "publicCertificate": "<publicCertificate>",
        "createdTime": "2021-03-11T19:50:03.50193Z",
        "changedTime": "2021-03-26T07:06:12.3232003Z"
      },
      "id": "/subscriptions/34adfa4f-cedf-4dc0-ba29-b6d1a69ab345/resourceGroups/testResourceGroup/providers/Microsoft.Logic/integrationAccounts/testIntegrationAccount/certificates/<integrationAccountCertificateName>",
      "name": "<integrationAccountCertificateName>",
      "type": "Microsoft.Logic/integrationAccounts/certificates"
    },
    {
      "properties": {
        "publicCertificate": "<publicCertificate>",
        "createdTime": "2021-05-27T12:45:33.455709Z",
        "changedTime": "2021-05-27T12:45:33.4564322Z"
      },
      "id": "/subscriptions/34adfa4f-cedf-4dc0-ba29-b6d1a69ab345/resourceGroups/testResourceGroup/providers/Microsoft.Logic/integrationAccounts/testIntegrationAccount/certificates/<integrationAccountCertificateName>",
      "name": "<integrationAccountCertificateName>",
      "type": "Microsoft.Logic/integrationAccounts/certificates"
    }
  ]
}

这是我当前的界面

export interface Certificate {
  value?: (ValueEntity)[] | null;
}

export interface ValueEntity {
  properties: Properties;
  id: string;
  name: string;
  type: string;
}
export interface Properties {
  publicCertificate: string;
  createdTime: string;
  changedTime: string;
}

我只需要显示publicCertificateidnametype 值。有没有更简单的方法来创建界面?

编辑

这是我目前使用的服务

@Injectable()
export class integrationAccountService
{
  constructor(private httpclient: HttpClient, private api: ApiService) { }

  getcertificates(): Observable<any> {
    const httpOptions : Object = {
      headers: new HttpHeaders({
        'Authorization': 'Token'
      }),
      responseType: 'json'
    };
    return this.httpclient.get('URL', httpOptions);
  }
}

组件

export class CertificateTableComponent {

  dataSource: MatTableDataSource<ValueEntity>;
  certificates: ValueEntity[] = [];
  columns: string[] = ['name', 'id', 'type', 'publicCertificate'];

  @ViewChild(MatSort, { static: true }) sort: MatSort;
  @ViewChild(MatPaginator, { static:true }) paginator: MatPaginator;

  constructor(private _integrationAccountService: integrationAccountService) {
  }

  ngOnInit() {

    this._integrationAccountService.getcertificates().subscribe(response => {
      this.certificates = response.data;

      this.dataSource = new MatTableDataSource(this.certificates);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;

    })

  }
}

显示数据的表格

 <table mat-table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>
      <td mat-cell *matCellDef="let row">{{ row.name }}</td>
    </ng-container>

    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Id</th>
      <td mat-cell *matCellDef="let row">{{ row.id }}</td>
    </ng-container>

    <ng-container matColumnDef="type">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Type</th>
      <td mat-cell *matCellDef="let row">{{ row.type }}</td>
    </ng-container>

    <ng-container matColumnDef="publicCertificate">
      <th mat-header-cell *matHeaderCellDef mat-sort-header>Public Certificate</th>
      <td mat-cell *matCellDef="let row">{{ row.publicCertificate }}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="columns"></tr>
    <tr mat-row *matRowDef="let row; columns: columns;"></tr>

  </table>

【问题讨论】:

  • 请贴一些您之前尝试过的代码,有助于理解您的问题
  • 我已经为服务、组件和表格添加了代码

标签: angular typescript


【解决方案1】:

尝试使用以下方法,它将您的响应对象转换为适当的响应,

getResponseArrayList(response): Array<PropertiesSource> {
    let resultList: PropertiesSource[] = [];
    resultList = response.value.map(data => {
      let res : PropertiesSource = data.properties.key.keyVault;
      res.publicCertificate = data.properties.publicCertificate;
      return res;
    });
    console.log('result ', resultList);
    return resultList;
  }

创建StackBlitz供您参考。

编码愉快.. :)

【讨论】:

  • @jonald 考虑将其标记为答案,如果它有助于解决您的查询..
【解决方案2】:

您的 JSON 示例数据似乎已损坏。您可以尝试https://jsonformatter.curiousconcept.com 进行更正。一旦它是正确的 JSON,我们可以更好地帮助您。

更新:

在您的服务中,如果您不返回“Observable”但指定已经存在的类型,那将会很有帮助。这样,当您在代码中的其他位置访问结果数据时,您将拥有更好的自动完成功能:

this.http.get>(languagesURL)

@Injectable()
export class integrationAccountService
{
  constructor(private httpclient: HttpClient, private api: ApiService) { }

  getcertificates(): Observable<Certificate> {
    const httpOptions : Object = {
      headers: new HttpHeaders({
        'Authorization': 'Token'
      }),
      responseType: 'json'
    };
    return this.httpclient.get<Certificate>('URL', httpOptions);
  }
}

在您的组件中,您必须首先对结果数据进行处理,没有“response.data”。一种方法是将接收到的数据扁平化为新结构:

export interface FlatRow {
    name: string;
    id: string;
    type: string;
    publicCertificate: string;
}

export class CertificateTableComponent {

  dataSource: MatTableDataSource<ValueEntity>;
  //certificates: ValueEntity[] = [];
  data: FlatRow[] = [];
  columns: string[] = ['name', 'id', 'type', 'publicCertificate'];

  @ViewChild(MatSort, { static: true }) sort: MatSort;
  @ViewChild(MatPaginator, { static:true }) paginator: MatPaginator;

  constructor(private _integrationAccountService: integrationAccountService) {
  }

  ngOnInit() {

    this._integrationAccountService.getcertificates().subscribe(response => {
      //this.certificates = response.data;
      this.data = [];
      if (response.value) {
          for (let entity of response.value) {
              let row: FlatRow = {
                  name: entity.name,
                  id: entity.id,
                  type: entity.type,
                  publicCertificate: entity.properties?.publicCertificate;
              };
          }
      }

      this.dataSource = new MatTableDataSource(this.data);
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;

    })

  }
}

【讨论】:

  • @JonaldMonday 我更新了我的帖子,希望对您有所帮助。
  • 感谢您的详细回复和解释。当我尝试实施您的解决方案时,我的表格行是空的,我不知道为什么。我没有收到任何错误,但数据没有进入表格
猜你喜欢
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 2018-11-27
  • 2019-10-06
  • 1970-01-01
相关资源
最近更新 更多