Drew13
Drew13

Reputation: 1371

Return value in function when service all is complete

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

Upvotes: 0

Views: 1556

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

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.

Upvotes: 1

Related Questions