Simon Rechermann
Simon Rechermann

Reputation: 501

NestJS Http Module

I took this example from the nestJS docs (https://docs.nestjs.com/techniques/http-module#http-module), which is a minimal example of my problem:

@Injectable()
export class CatsService {
  constructor(private httpService: HttpService) {}

  findAll(): Observable<AxiosResponse<Cat[]>> {
    return this.httpService.get('http://localhost:3000/cats');
  }
}

How can I extract the actual Array of Cats from the Observable<AxiosResponse<Cat[]>>? I tried the following but it gives me a subscriper object which I also don't know how to unwrap to get the actual data.

const cats = await this.catsService.findAll().subscribe((val) => val);

Upvotes: 1

Views: 10917

Answers (3)

Islam Hanafi Mahmoud
Islam Hanafi Mahmoud

Reputation: 1190

Using .toPromise() is deprecated now check this : https://rxjs.dev/deprecations/to-promise

Listing below is an example using the new approach

UPDATE Oct 2021

import { lastValueFrom } from 'rxjs';

.
.
.

const observable = await this.httpService.get('url').pipe(map((res) => res.data));

// you can use the data object now !!
const data = await lastValueFrom(observable);


Upvotes: 8

Simon Rechermann
Simon Rechermann

Reputation: 501

@Injectable()
export class CatsService {
  constructor(private httpService: HttpService) {}

  findAll(): Promise<Cat[]> {
    return this.httpService.get('http://localhost:3000/cats').toPromise();
  }

}

const cats = await this.catsService.findAll().data

worked for me.

Upvotes: 2

plusheen
plusheen

Reputation: 1436

Try this:

  findAll(): Observable<Cat[]> {
    return this.httpService.get('http://localhost:3000/cats')
      .pipe(map(response => response.data);
  }

Upvotes: 1

Related Questions