繁体   English   中英

如何使用嵌套数组为 object 创建接口

[英]How to create interface for object with a nested array

我正在创建一个简单的 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>

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

更新:

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

this.http.get<Response<ExtLanguage[]>>(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;

    })

  }
}

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

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供您参考。

快乐编码.. :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM