0

我在 Angular 中使用NGX 芯片。我将输入的芯片保存到 Firebase 并检索它们。

问题是,当它尝试渲染保存的芯片时,它不能并抛出错误。

在发布此问题之前,我尝试在 GitHub 上阅读并关注此问题,并添加了displayByandidentifyBy标记,但无济于事。

错误

Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

HTML 代码

<tag-input 
     (onAdd)="onCategoryAdded($event, product.external_id)" 
    [displayBy]="'display'"
    [identifyBy]="'$key'" 
    [(ngModel)]="product.categories"
    [ngModelOptions]="{standalone: true}"
    theme="minimal" 
    placeholder="Categories"
>
 <tag-input-dropdown [autocompleteItems]="categories"></tag-input-dropdown></tag-input>
</tag-input>

在我的控制器中,我设置了一个可观察项,监听值变化并将其分配给提到的可观察项。

public products: Observable<any[]>;

ngOnInit() {
   this.products = this.afd.list('/products').valueChanges();
}

onCategoryAdded(event, product) {
  this.afd.database.ref('/products').orderByChild('external_id').equalTo(product).once('value', (snapshot) => {
    snapshot.forEach((product) => {
      this.afd.database.ref('/products').child(product.key).child('categories').push({
        'display' : event.display,
        'value' : event.value
      });
    });
  });
}

product.categories{{product.categories | json}}当我添加到我的 html时,打印出来如下所示。

{ "-LfN8VhSrWBye-8ukSAq": { "display": "Featured", "value": "Featured" } }

我应该更改在 Firebase 中保存类别的方式,以便它返回不同的值,还是应该在控制器中以某种方式转换返回的值?

4

1 回答 1

0

正如错误 NGX-CHIPS is waiting for an array and you are passing an object 中所述

Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

您将其传递给 NGX-CHIPS


{ "-LfN8VhSrWBye-8ukSAq": { "display": "Featured", "value": "Featured" } }

您需要将此 json/object 转换为数组,您可以使用 map 运算符执行此操作

// don't forget to import the operator

import { map } from 'rxjs/operators'


ngOnInit() {
   this.products = this.afd.list('/products').valueChanges().pipe(
map(list => {

      const productsArray = Object.keys(list).map(key => {
         const item = list[id]; // [{display: 'Featured', value: 'Featured'}]
         item.key = key;  // [{key: "-LfN8VhSrWBye-8ukSAq", display: 'Featured', value: 'Featured'}]
         return item;
      });

   }));
}


于 2019-05-21T02:44:10.437 回答