首页 > 解决方案 > Angular - 将 API 响应推送到数组中

问题描述

我有一种情况,我需要将调用的 API 的响应推送到数组。以前,我像这样对数据进行硬编码。

filterrole = [
{ text: 'Supervisor', value: 'Supervisor' },
{ text: 'Administrator', value: 'Administrator'},
{ text: 'Maintainer', value: 'Maintainer' }
];

但是现在,我需要从后端获取数据。后端查询很好。这就是后端调用的结果。

["Supervisor","Maintainer","Observer","Administrator"]

filterrole 有它自己的类,由文本和值变量组成。

角色类

export class Role {
text: string;
value: string;
}

我的问题是,如何将 API 调用的响应推送到 filterrole 变量中?下面是我的解决方法。

export class AddGroupComponent implements OnInit {
     filterrole: Role [];
     ngOnInit() {
          this.getDistinctRole();
     }

     getDistinctRole(): void {
     this._dashboardservice.getDistinctRole().subscribe(
        resp => {
           // what should i do here to push the data into
           // filterdata.text and filterdata.value
        },
        err => {
           this.loading = false;
           this._nzMessage.create('error', `Error occurred: ${err.message}`);
       }
     );
 }

标签: angulartypescript

解决方案


你也可以这样做

export class AddGroupComponent implements OnInit {
     filterrole = [];
     ngOnInit() {
          this.getDistinctRole();
     }

     getDistinctRole(): void {
     this._dashboardservice.getDistinctRole().subscribe(
        resp => {
           this.fliterRole(resp);
        },
        err => {
           this.loading = false;
           this._nzMessage.create('error', `Error occurred: ${err.message}`);
       }
     );
      filterRole(result) {
         for(let i =0; i < result.length; i++) {
            this.filterrole.push({ text: result[i], value: result[i] });
       }
 }

这是工作示例 https://codesandbox.io/s/525xw2097n


推荐阅读