首页 > 解决方案 > Angular如何从数据库中获取数组并将元素推入其中

问题描述

我正在使用 Firebase,我有一个带有单词的“字典”,每个单词都有不同的定义。我正在尝试从后端获取包含特定单词定义的数组并将新定义添加到其中。

数据应该是这样的:

words 
    'Word1'
        'Definitions'
            'Definition1'
            'Definition2'
    'Word2'
        'Definitions'
            'Definition1'

我所做的是,但我无法从值更改中获取属性“定义”:

let data = {
  name: word,
  definitions: [],
}

let newDefinition = 'Some definition'

let obj = this.db.object(`words/${word}`);

let obs = obj.valueChanges().subscribe(x => {
  changes = x;

  // If the word doesn't exist, create it.
  if (x === null) {
    data.definitions.push(this.newDefinition);
    obj.set({ definitions: data.definitions, word: data.word });

  // If the word exists add the definition to its list.
  } else {
    data.definitions = x.definitions;
    data.definitions.push(this.newDefinition);

    obj.update({ definitions: data.definitions });
  }
  obs.unsubscribe();
});

标签: angularfirebaseangularfire

解决方案


最简单的方法是将xto 转换为any

data.definitions = (<any>x).definitions;

但是为了完整性,您应该使用 TypeScript 接口来定义从数据库中获取的数据的结构。


推荐阅读