Home > Software design >  Angular-cli ver 13.3.7 Subscribe ERROR this.data is undefined
Angular-cli ver 13.3.7 Subscribe ERROR this.data is undefined

Time:07-08

I want to return array from [Firebase] Realtime Database

This is my code:

add-student.component.ts

ngOnInit() {
    this.crudApi.GetStudentsList();
    this.studenForm();
    this.crudApi.GetStudentsList().snapshotChanges().subscribe(data =>{
      this.data = data;
    })
    console.log(this.data); // line 28
}

curd.service.ts

GetStudentsList() {
    this.studentsRef = this.db.list('students-list');
    return this.studentsRef;
}

Error Message:

undefined
add-student.component.ts:28:12 ERROR TypeError: this.data is undefined

Can someone tell me, how to solve this problem or is there any other way to return data from firebase realtime database to my variable?

CodePudding user response:

You need to declare data

export class HelloComponent implements OnInit {
    data = [];
....
]

CodePudding user response:

Here the subscribe which you are trying is asynchronous. So if try, to console the data value on line 28 which is outside the callback won't have the value. So, once we receive the success call back, we could try logging the value inside the success callback. Please refer the snippet below:

ngOnInit() {
  this.crudApi.GetStudentsList();
  this.studenForm();
  this.crudApi.GetStudentsList().snapshotChanges().subscribe(data =>{
    this.data = data;
    console.log(this.data); // Here we could see the value coming from service.
  });
}

Hope this helps.

  • Related