在角度2中使用Observable of array

时间:2017-02-16 16:51:07

标签: angular typescript rxjs observable

我有以下代码:

  get items():Observable<MenuItem[]>{

  let items: MenuItem[] =  [
      {
       label: "incidents_dialog_tab_actions_measures_defined"
      },
      {
       label: "incidents_dialog_tab_actions_measures_with_supplier_agreed"
      },
      {
        label: "incidents_dialog_tab_actions_measures_are_implemented"
      },
      {
        label: "incidents_dialog_tab_actions_measures_are_effective"
      }
  ];

  return  Observable.from(items).mergeMap( obj => this.commonModel.translate(obj.label)).bufferCount(items.length);
}

this.commonModel.translate(obj.label)返回一个observable。

在我的模板中,我像[model]="items | async"一样使用它,项目应该是包含格式为{ label: translation}的翻译的数组的可观察对象。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

您需要向.map()添加this.commonModel.translate以继续转换返回的翻译并为其提供所需的形状:

Observable.from(items)

 // Call the translation service for each item.
 .mergeMap(item =>
   this.commonModel.translate(item.label)
     // Store the translation in an object with the shape you want.
     .map(translatedLabel => ({ label: translatedLabel }))
 )

 // Use this to put back all translated items in a single array again.
 .toArray();