angular - 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}`);
}
);
}
解决方案
你也可以这样做
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] });
}
}
推荐阅读
- c# - How to modify JSON to custom structure
- java - SmsReceiver onReceive 后短信消失
- java - JSP 文件中的 doGet 有效,但 doPost 无效
- ios - 自定义单元格宽度?
- python - Django如何将一个字段的(.count)乘以另一个字段并在模板中显示结果
- html - 在裁剪和居中的图像下方创建带有文本的缩略图库
- java - 在 SparkStreaming 中没有得到输出
- html - 创建一个 CSS 按钮以在单击时显示 x 数量的文本并更改 div 标签的大小
- python - 如何获取“HTTPS”链接以及如何在 python 中将 epub 转换为 txt?
- laravel - Laravel 在涉及三个表的数据透视表上连接数据