【发布时间】:2016-02-03 10:51:46
【问题描述】:
我正在构建非常简单的 Angular2,它通过使用“firebase-angular2”npm 模块与 Firebase 对话。我设法将它发布到 Firebase 没有问题。
问题:
- 我无法让“items”从“itemsarr”中获取值,我收到错误:未捕获的 TypeError:无法设置未定义的属性“items”。我尝试直接设置:this.items.push(records.val());,但我得到同样的错误。
- 在第 14 行,我看到数组中的所有项目,但每次更新时它都会在控制台数组中列出,所以如果我有 50 个项目,它将在控制台中列出 50 次。我知道我应该把它移到外面,但请看问题 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 }
【问题讨论】:
标签: javascript ecmascript-6 angular