rxjs 新手上路, 在使用 nestjs 中用到了 HttpModule, 是基于 rxjs 封装的一个 axios, 在用的过程中不熟悉 rxjs 的用法, 官网来来回回看了好久了, 不得方法 结果达不到预期, 请教一下大佬正确的姿势. 谢谢
import { HttpModule } from '@nestjs/axios';
@Module({
imports: [
HttpModule.register({
baseURL: 'https://jsonplaceholder.typicode.com',
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
// controller
@Get('/')
getHello() {
return this.appService.getHello();
}
// service
import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { map } from 'rxjs';
@Injectable()
export class AppService {
constructor(private httpService: HttpService) {}
getHello() {
return this.httpService.get('/users').pipe(
map((res) => res.data),
map((data) => {
return data.map((user) => {
user.name = user.name.toUpperCase();
user.posts = [];
if (user.id % 2 === 0) {
// 当符合条件时,需要获取到对应的 posts 并 push 给当前的 user
this.httpService.get('/posts/' + user.id).pipe(
map((post) => {
user.posts.push(post.data);
}),
);
}
return user;
});
}),
map((res) => {
return res;
}),
);
}
}
[
{
"id": 1,
"name": "LEANNE GRAHAM",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": { "lat": "-37.3159", "lng": "81.1496" }
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
},
"posts": []
},
{
"id": 2,
"name": "ERVIN HOWELL",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": { "lat": "-43.9509", "lng": "-34.4618" }
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
},
"posts": ['postObject1']
}
]
"dependencies": {
"@nestjs/axios": "^0.0.7",
"@nestjs/common": "^8.0.0",
"@nestjs/core": "^8.0.0",
"@nestjs/platform-express": "^8.0.0",
"axios": "^0.26.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0"
},
这里写了一个基于 promise 实现需求的例子, 希望大佬提供一个切换成 rxjs 实现的例子 点击这里 codePen
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.