I've looked at similar questions on StackOverflow but none of them match my specific problem:
I have a TypeScript function in an Angular 6 service, calling a function in another service like this:
Service1:
myArray: Array<IMyInterface>
...
getArray(): Observable<IMyInterface[]> {
this.myArray= this.service2.getAnArray(1);
return Observable.of(this.myArray);
}
Service2
getAnArray(myEntityId): Array<IMyInterface> {
const myArray2: IMyInterface[] = [];
this.getConnection().then(connection => {
connection.invoke('GetEntityById', myEntityId).then((someJson: any) => {
someJson.forEach( x => myArray2.push(x));
return myArray2;
})
});
}
It gives me the error in Service2 A function whose declared type is neither 'void' nor 'any' must return a value.
I need to return myArray2 after connection.invoke('GetEntityById', myId) has resolved, as the array is only populated after that resolves, which is why I try to do it inside then.
How do I do this?
This may/may not suit your needs, but you could just return the Promise from your service method, eg:
getAnArray(myEntityId) {
const myArray: IMyInterface[] = [];
// Note the return here
return this.getConnection().then(connection => {
return connection.invoke('GetEntityById', myEntityId).then((someJson: any) => {
someJson.forEach( x => myArray.push(x));
return myArray;
})
});
}
Your calling code would then look like
getAnArray(someId).then(function(theArray) {. . .});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With