0

Using Angular 5. A component calls a service. This service must call another service before making a server call. I am not able to get the result asynchronously in the component. I use ellipses for brevity below.

Component:

...
import { SystemOnlineService } from '../services/system-online.service';
...
constructor(private sys: SystemOnlineService) {
    sys.getStatus()
    .then(result => {
        console.log(result);
    });
}

SystemOnlineService:

import { Injectable } from '@angular/core';
import { Wakanda } from './wakanda.service';
import 'rxjs/add/operator/toPromise';
...
getStatus() {

    this.wakanda.getCatalog()
    .then((ds) => {
        this.ds = ds;
        this.ds.Rpc_reportObjectHelper.isMySystemUp()
        .then(statusArr => {
            return statusArr;
        });
    });
}

The component throws this error about the sys.getStatus() call:

Uncaught (in promise): TypeError: Cannot read property 'then' of undefined

If I console.log(sys.getStatus());, it logs undefined.

I think I am just missing something about how to properly make async calls.

NAMS
  • 983
  • 7
  • 17

1 Answers1

5

the 'getStatus()' should return a promise. Now, it is returning nothing. You can rewrite this way:

getStatus() {

  return new Promise( resolve => {
    this.wakanda.getCatalog()
    .then((ds) => {
        this.ds = ds;
        return this.ds.Rpc_reportObjectHelper.isMySystemUp()
        .then(statusArr => {
            resolve(statusArr);
        });
    });
  })
}

Or, event better, if this block of code does not have any toher logic, you can remove unecessary code (using arrow functions):

getStatus() {
  return new Promise( resolve => {
    this.wakanda.getCatalog()
    .then( ds => ds.Rpc_reportObjectHelper.isMySystemUp().then( data => resolve(data)) )
  })
}
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71
  • also you should call the method on ngOnInit method because is going to be called only once if you put the code in the constructor – Ricardo Feb 20 '18 at 15:33
  • Thank you, this code worked correctly for me. I'll remember to return a promise for functions that are run asynchronously. – NAMS Feb 20 '18 at 16:46
  • Also Ricardo wouldn't the code be called only once even if i would put it in ngOnInit()? – NAMS Feb 20 '18 at 16:48