Angular 如何从数据库中获取一个数组并将一个元素压入其中
Angular how to get an array from the database and push an element into it
我正在使用 Firebase,我有一个 'dictionary' 的单词,每个单词都有不同的定义。我正在尝试从后端获取包含某个单词定义的数组,并将新定义添加到其中。
数据应该是这样的:
words
'Word1'
'Definitions'
'Definition1'
'Definition2'
'Word2'
'Definitions'
'Definition1'
我所做的是,但我无法从值更改中获取 属性 'definitions':
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();
});
最简单的方法是将 x
转换为 any
:
data.definitions = (<any>x).definitions;
但为了完整性,您应该使用 TypeScript 接口来定义从数据库中获取的数据的结构。
我正在使用 Firebase,我有一个 'dictionary' 的单词,每个单词都有不同的定义。我正在尝试从后端获取包含某个单词定义的数组,并将新定义添加到其中。
数据应该是这样的:
words
'Word1'
'Definitions'
'Definition1'
'Definition2'
'Word2'
'Definitions'
'Definition1'
我所做的是,但我无法从值更改中获取 属性 'definitions':
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();
});
最简单的方法是将 x
转换为 any
:
data.definitions = (<any>x).definitions;
但为了完整性,您应该使用 TypeScript 接口来定义从数据库中获取的数据的结构。