【问题标题】:Angular2 firebase retrieve and assign vars [duplicate]Angular2 firebase检索和分配变量[重复]
【发布时间】:2016-02-03 10:51:46
【问题描述】:

我正在构建非常简单的 Angular2,它通过使用“firebase-angular2”npm 模块与 Firebase 对话。我设法将它发布到 Firebase 没有问题。

问题:

  1. 我无法让“items”从“itemsarr”中获取值,我收到错误:未捕获的 TypeError:无法设置未定义的属性“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 }

【问题讨论】:

    标签: javascript ecmascript-6 angular


    【解决方案1】:

    您应该使用箭头函数才能使用与组件本身对应的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

    希望对你有帮助 蒂埃里

    【讨论】:

      【解决方案2】:

      使用

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

      而不是

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-25
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-26
        • 1970-01-01
        相关资源
        最近更新 更多