Undefined Data when parsing outside async function in Angular

ryard firdaus2 :

I have a stuck when I want to parse the data, which get from http call, and parsing it to ngOnInit. Can you help me to solve this problem? I am using Angular 4. Thanks :)

the async function :

async getAsyncData() {
      this.asyncResult = await this.serviceDashboard.getAllGeografika().toPromise().then(data => {
        return data.length;
      });
      return this.asyncResult;
}

ngOnInit where I want to print the data:

ngOnInit() {
      console.log('Halo from ngOnInit');
      console.log('print data :' +  this.getAsyncData();
}
Kurt Hamilton :

You're not awaiting the promise from your function, so this:

 console.log('print data :' +  this.getAsyncData();

Is logging the promise, not the resolved value of the promise

You can resolve this in at least three ways:

1. Use async/await

async ngOnInit() {
  console.log('Halo from ngOnInit');
  const data = await this.getAsyncData();
  console.log('print data :' + data);
}

async getAsyncData() {
  const data = await this.serviceDashboard.getAllGeografika().toPromise();
  return data.length;
}

This kind of breaks the contract of OnInit, but you can get away with it.

2. Resolve the promise

This is probably a purer form than the last, but you may not like how verbose it is.

ngOnInit() {
  console.log('Halo from ngOnInit');
  this.getAsyncData().then(data => {
      console.log('print data :' + data);
  });
}

async getAsyncData() {
  const data = await this.serviceDashboard.getAllGeografika().toPromise();
  return data.length;
}

3. Use RxJS

My preferred option.

ngOnInit() {
  console.log('Halo from ngOnInit');
  this.getAsyncData().subscribe(data => {
      console.log('print data :' +  data.length);
  });
}

getAsyncData(): Observable<any> {
  return this.serviceDashboard.getAllGeografika();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29795&siteId=1