admin管理员组

文章数量:1279144

I took this example from the nestJS docs (), 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);

I took this example from the nestJS docs (https://docs.nestjs./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);
Share Improve this question asked Jun 15, 2021 at 12:12 Simon RechermannSimon Rechermann 5011 gold badge7 silver badges24 bronze badges 1
  • try await this.catsService.findAll().toPromise(); – Micael Levi Commented Jun 15, 2021 at 15:55
Add a ment  | 

3 Answers 3

Reset to default 8

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);


@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.

Try this:

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

本文标签: javascriptNestJS Http ModuleStack Overflow