首页 > 解决方案 > 在 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;

为什么这行得通,而不是我的第一次实施?

标签: angular

解决方案


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()

推荐阅读