无法使用打字稿中的数组读取 属性 of null

Cannot read property of null with arrays in typescript

我是打字稿的新手。我已尝试在此处搜索答案,但 none 的解决方案似乎适合。

我有一个相对简单的(我猜)问题。 我使用 profilesArr 数组获得的数据是正确的,但我似乎无法将该数据传递到我在 class 开头声明的数组 "profiles"。但是,它确实将数据从 profilesArr 正确传递到本地声明的名为 "array" 的数组。我可以轻松地从 "array" 获取数据,但是当我 运行 这行代码时 this.profiles[i]=profilesArr[k];它给了我错误:无法读取 属性 'profiles' of 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);
  }

我知道这是一个非常新手的问题,但我无法理解它。如果您能帮我解决问题,我将真的感激不尽,谢谢!

替换:

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) => { ... }