我在Angular中使用NGX-Chips。我将键入的筹码保存到Firebase中并进行检索。
问题是,当它尝试呈现已保存的芯片时,它无法并引发错误。
在发布此问题之前,我尝试在GitHub上通读并关注此问题,并添加了displayBy
和identifyBy
标签,但无济于事。
错误
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
});
});
});
}
当我在HTML中添加product.categories
时, {{product.categories | json}}
如下打印。
{ "-LfN8VhSrWBye-8ukSAq": { "display": "Featured", "value": "Featured" } }
我应该更改在Firebase中保存类别的方式,以便它返回不同的值,还是应该在控制器内以某种方式转换返回的值?
答案 0 :(得分:0)
正如错误NGX-CHIPS中所述,正在等待数组,并且您正在传递对象
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;
});
}));
}