Observables in angular?

In the below class when i try to console.log the datas property after completing subscription it printing undefined why is that ? Though it is populated by the service ?

export class AppComponent {

  datas: any;
  constructor(private service: SpacexServiceService) {

    this.service.get_data().
      subscribe(res => this.datas = this.flatten(res),
        error => console.log('Error happened' + error),
        function () {
          console.log(this.datas);
        });
  }



  flatten(obj) {
    const result = {};
    for (const i in obj) {

      if (typeof obj[i] === 'object') {
        const flatobj = this.flatten(obj[i]);

        for (const x in flatobj) {
          result[i + '_' + x] = flatobj[x];
        }
      } else {
        result[i] = obj[i];
      }
    }

    return result;

  }

}

This is because by using a regular function as the onCompleted callback, this refers to the stream on which it got called; use an arrow function here instead as these don’t have their own this-bindings (see here for details).

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.