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
3 Answers
Reset to default 8Using .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
版权声明:本文标题:javascript - NestJS Http Module - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741278135a2369849.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论