0

我是打字稿的新手。我试过在这里搜索答案,但似乎没有一个解决方案适合。

我有一个相对简单的(我猜)问题。我使用profilesArr 数组获得的数据是正确的,但我似乎无法将该数据传递给我在课程开始时声明的数组“profiles”。但是,它确实将数据从profilesArr 正确传递到本地声明的名为“array”的数组。我可以轻松地从“数组”中获取数据,但是当我运行这行代码时 this.profiles[i]=profilesArr[k]; 它给了我错误:无法读取 null 的属性“配置文件”。

export class RegisteredusersPage {

  private profileListRef = this.db.list<Profile>('profile-list');
  constructor(public navCtrl: NavController, public navParams: NavParams,     private storage: Storage,
    private db: AngularFireDatabase) {
  }
  profiles=[];
  ionViewDidLoad() {
    console.log('ionViewDidLoad RegisteredusersPage');

  }
  getProfile(){
    console.log(this.db.list('profile-list'));
    var database = firebase.database();
    var ref=database.ref("profile-list");
    ref.on('value', this.gotData, this.errData)

  }
  gotData(data){
      console.log(data.val());
      var profilesArr=data.val();
      var keys=Object.keys(profilesArr);
      var that=this;
      var array=[];
      console.log("Pre keys");
      console.log("keys:"+keys);
      console.log("profilesArr: "+profilesArr);
      for(var i = 0; i <keys.length; i++){
          var k = keys[i];
          var profileName = profilesArr[k].name;
          var profileCountry = profilesArr[k].country;
          console.log(profileName,profileCountry);
          alert(profileName);
          alert(profileCountry);
          array[i]=profilesArr[k];
          this.profiles[i]=profilesArr[k];

      }
      console.log(this.profiles);

  }
  errData(err){
    console.log("Error");
    console.log(err);
  }

我知道这是一个相当新手的问题,但我无法理解它。如果您能帮我解决这个问题,我将不胜感激,谢谢

4

1 回答 1

0

代替:

ref.on('value', this.gotData, this.errData)

和:

ref.on('value', this.gotData.bind(this), this.errData.bind(this))

或者:

ref.on('value', (data) => this.gotData(data), (err) => this.errData(err))

或者,更改定义:

gotData(data){ ... }
errData(err){ ... }

到:

gotData = (data) => { ... }
errData = (err) => { ... }
于 2018-08-15T20:09:39.053 回答