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