angular - 在 ngOnInit 中使用 foreach 将数据推送到数组中
问题描述
为了填充多选下拉列表,我想请求我的 Web 服务,从中获取数据,然后创建一个包含特定对象的自定义数组,这与我从 WS 获得的对象不同。
我希望能够在 ngOnInit 中执行此操作,以便在加载页面时已填充此多选下拉列表。
我唯一的问题是 Angular 似乎不想让我在一个带有 ngOnInit 内部的 forEach 的数组中推送东西。它没有给出任何错误,只是没有填满我的数组。
这是一些代码:
fonctions: any[];
dropdownList = [];
ngOnInit() {
this.serviceFct.getAll()
.subscribe(response => {
this.fonctions = response as any;
this.fonctions.forEach(element => {
this.dropdownList.push({item_id: element.idFct, item_text: element.nomFct });
});
});}
但是,如果我尝试用一个按钮用相同的 foreach 填充相同的数组,它就像一个魅力。为什么以及如何解决它?
编辑:那里的答案给了我尝试一些有效的想法:
let dropdown = [];
this.fonctions.forEach(element => {
dropdown.push({item_id: element.idFct, item_text: element.nomFct });
});
this.dropdownList = dropdown;
为什么这行得通,而不是我的第一次实施?
解决方案
The "pro" way to do it.
import { map } from 'rxjs/operators';
.
.
.
ngOnInit():void {
this.serviceFct.getAll().pipe(
map(res=> {
return res.map(element=>({item_id: element['idFct'], item_text: element['nomFct'] }))
})).subscribe(data => {
this.dropdownList = data;
});
}
If you do this, don't forget to unsubscribe in the ngOnDestroy()
. Every time you use subscribe you must unsubscribe
unless you using the async
pipe which does it for you.
To learn more about susbcriptions
The "more pro" way to do it
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
.
.
.
$dropdownList: Observable<[]>;
...
ngOnInit():void {
this.$dropdownList = this.serviceFct.getAll().pipe(
map(res=> {
return res.map(element=>({item_id: element['idFct'], item_text: element['nomFct']
}))
}))'
}
IN YOUR HTML
<YOUR DROP DOWN ELEMENT>
<BLAH *ngFor="let element of $dropdownList | async"></BLAH>
</YOUR DROP DOWN ELEMENT>
Extra Tips:
- The async pipe subscribes and unsubscribes for you
- specify void or the return type of your funcions (is good practice)
- Try to avoid using any and create an model (interface or class)
- Create a function with all this logic and call it in the
ngOnInit()
推荐阅读
- math - 在 3D 上计算矢量的方向
- php - 方法 Illuminate\Validation\Validator::validateAdmin 不存在
- node.js - 使用引用参数在主对话框中导航
- javascript - 在 fetch().then() 后页面不断刷新,并承诺(e.preventDefault() 已设置)
- typescript - TypeORM 抛出错误 'ER_CANT_CREATE_TABLE: Can\'t create table `test`.`comment`
- c# - 如何 ace.js 编辑器删除红色空格点?
- ruby-on-rails - 如何使用 Rails 5 将 SCA Stripe Checkout 与 Stripe Connect 集成
- vbscript - 有没有办法在 VBS 中导出变量?
- python - 在添加新列时计算 Pandas 中的时间差
- hadoop - 了解 Hadoop 生态系统的最佳方式是什么