【问题标题】:NGX-CHIPS not rendering Firebase returned listNGX-CHIPS 不呈现 Firebase 返回列表
【发布时间】:2019-05-21 02:27:58
【问题描述】:

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

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

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

错误

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 | json}} 添加到我的html 时,product.categories 会打印如下。

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

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

【问题讨论】:

    标签: angular typescript firebase-realtime-database ngx-chips


    【解决方案1】:

    正如错误 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;
          });
    
       }));
    }
    
    
    

    【讨论】:

    • idlist[id] 中定义的位置在哪里。这也操纵了整个产品阵列。这些类别是产品的子类别。
    • 关于我们如何过滤每个产品的对象有什么想法吗?
    • Firebase 不返回数组,而是返回一个对象,因此如果您想遍历它们,您必须将该对象转换为数组。就像我在回答中所做的那样。但是您仍然需要一个标识符才能在更新文档时引用它,这就是为什么我将每个对象键添加到该数组中的每个对象中
    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多