Angular2 火力基地检索并分配变量

Angular2 firebase retrieve and assign vars

本文关键字:分配 变量 检索 Angular2      更新时间:2023-09-26

我正在构建非常简单的Angular2,它通过使用"firebase-angular2"npm模块与Firebase进行通信。我设法让它毫无问题地发布到 Firebase。

问题:

  1. 我无法使"项目"从"itemsarr"中获取值,出现错误:未捕获类型错误:无法设置未定义的属性"项目"。我尝试直接设置: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 }

解决方案(感谢蒂埃里(

我需要先将"=[]"设置为项目,然后转换为箭头函数,然后一切正常。不知道箭头功能,这是以这种方式连接的。

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。

希望对您有所帮助,蒂埃里

使用

childSnapshot, prevChildKey = { ... }
records => { ... }

而不是

function(childSnapshot, prevChildKey) { ... }
function(records) { ... }