gpt4 book ai didi

javascript - Angular2 firebase 检索并分配变量

转载 作者:行者123 更新时间:2023-11-27 23:23:33 26 4
gpt4 key购买 nike

我正在构建非常简单的 Angular2,它通过使用“firebase-angular2”npm 模块与 Firebase 进行通信。我成功地将其发布到 Firebase,没有出现任何问题。

问题:

  1. 我无法使“items”从“itemsarr”获取值,我收到错误:未捕获类型错误:无法设置未定义的属性“items”。我尝试直接设置:this.items.push(records.val());,但我得到同样的错误。
  2. 在第 14 行,我看到数组中的所有项目,但每次更新时它都会在控制台数组中列出,因此如果我有 50 个项目,它将在控制台中列出 50 次。我知道我应该把它移到外面,但请看问题 3。
  3. 在第 16 行,我在 itemsarr 中没有看到任何内容,它是空的?!

代码:

1 var itemsarr = [];
2 @Component({
template:`
<li *ngFor="#item of items">
{{item.title}}
</li>
`
})
3 export class AppComponent {
4
5 items:Array<string>;
6
7 constructor() {
8
9
10 myFirebaseRef.on('child_added', function(childSnapshot, prevChildKey) {
11 childSnapshot.forEach(function(records) {
12 this.items = itemsarr.push(records.val());
13 });
14 console.log(itemsarr)
15 });
16 console.log(itemsarr)
17 }
18 }
19 }

解决方案(感谢蒂埃里)

我需要先将“=[]”设置为项目,然后转换为箭头函数,然后一切都没有问题。不知道箭头函数和 this 是这样联系的。

1 
2 @Component({
template:`
<li *ngFor="#item of items">
{{item.title}}
</li>
`
})
3 export class AppComponent {
4
5 items:Array<string>=[];
6
7 constructor() {
8
9
10 myFirebaseRef.on('child_added', (childSnapshot, prevChildKey) => {
11 childSnapshot.forEach((records) => {
12 this.items.push(records.val());
13 });
14
15 });
16
17 }
18 }
19 }

最佳答案

您应该使用箭头函数才能使用与组件本身相对应的 this 关键字。

export class AppComponent {
items:Array<string>;

constructor() {
myFirebaseRef.on('child_added', (childSnapshot, prevChildKey) => {
childSnapshot.forEach((records) => {
this.items = itemsarr.push(records.val());
});
console.log(itemsarr)
});
console.log(itemsarr);
}
}

有关箭头函数的词法 this 的更多提示,请参阅此链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions .

希望对你有帮助蒂埃里

关于javascript - Angular2 firebase 检索并分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35175019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com