0

I have a function where I want to return an array. This function makes a service call to my backend so I want to return the array when I know my service call is complete.

getList(id: number): MyArray[] {
    let temp: MyArray[] = [];
    this.service.getById(id).subscribe(
      singleId => {
        temp = temp.concat(singleId);
      },
      () => {},
      () => {
        this.myArray= temp;
        return temp;
      }
    );
  }

But when I compile my code it still gives me the error

A function whose declared type is neither 'void' nor 'any' must return a value.

If I return temp outside of the subscribe function, it returns nothing since the service call is not actually complete

Drew13
  • 1,301
  • 5
  • 28
  • 50
  • [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Mar 02 '20 at 13:25
  • Does this answer your question? [Get observable return value without subscribing in calling class](https://stackoverflow.com/questions/60489200/get-observable-return-value-without-subscribing-in-calling-class) – Shravan Mar 02 '20 at 17:02

1 Answers1

1

If you want to return the array from getList, then it has to be Observable, and whatever calls it will subscribe to the returned observable.

If you want to perform an operation, such as pushing the result into an array, you can do this in a tap operator in the pipe.

If you want to return the array that you're adding to, you can map to that array.

getList(id: number): Observable<MyArray[]> {
  return this.service.getById(id).pipe(
    tap(single => this.myArray.push(single)),
    map(() => this.myArray)
  );
}

This isn't a particularly useful function, but it demonstrates how you return a result from an asynchronous call.

Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40