使用 RxJS 重构嵌套 API 调用
Refactor nested API calls with RxJS
这是我需要重构的内容:
- 调用
API/GetUser
,获取结果,提取user.id
,保存结果(user
)
- 从第一次调用开始用
id
调用 API/GetMoreUserData/{userId}
,保存结果 (moreData
)
- 将结果
{u: user, d: moreData }
和return构造对象给调用者
我目前正在使用嵌套调用来完成此操作,但我确信使用 RxJS 有更好的方法。
你可以使用pipe和switchMap,这里是一个随机的例子:
this.activatedRoute.params.pipe( //params returns an observable
switchMap(({id}) => this.buyerService.getDetails(id)) //getDetails returns an observable
)
.subscribe(h => {
console.log(h)
}
这就是 switchMap
的用途。
@Injectable({ providedIn: 'root' })
export class UserService {
getUser(): Observable<any> {
//mock implementation, probably would be an HTTP get
return of({ id: 42 });
}
getMoreUserData(id: number): Observable<any> {
//mock implementation, probably would be an HTTP get
return of({ username: 'batman', id: id });
}
getAllTheUserData(): Observable<any> {
return this.getUser().pipe(
switchMap((userResp) => {
const userId = userResp.id;
return this.getMoreUserData(userId).pipe(
map((moreUserResp) => {
//spread operator to combine to two objects
return {
...userResp,
...moreUserResp,
};
})
);
})
);
}
}
Here's a stackblitz 演示服务及其用法。
这是我需要重构的内容:
- 调用
API/GetUser
,获取结果,提取user.id
,保存结果(user
) - 从第一次调用开始用
id
调用API/GetMoreUserData/{userId}
,保存结果 (moreData
) - 将结果
{u: user, d: moreData }
和return构造对象给调用者
我目前正在使用嵌套调用来完成此操作,但我确信使用 RxJS 有更好的方法。
你可以使用pipe和switchMap,这里是一个随机的例子:
this.activatedRoute.params.pipe( //params returns an observable
switchMap(({id}) => this.buyerService.getDetails(id)) //getDetails returns an observable
)
.subscribe(h => {
console.log(h)
}
这就是 switchMap
的用途。
@Injectable({ providedIn: 'root' })
export class UserService {
getUser(): Observable<any> {
//mock implementation, probably would be an HTTP get
return of({ id: 42 });
}
getMoreUserData(id: number): Observable<any> {
//mock implementation, probably would be an HTTP get
return of({ username: 'batman', id: id });
}
getAllTheUserData(): Observable<any> {
return this.getUser().pipe(
switchMap((userResp) => {
const userId = userResp.id;
return this.getMoreUserData(userId).pipe(
map((moreUserResp) => {
//spread operator to combine to two objects
return {
...userResp,
...moreUserResp,
};
})
);
})
);
}
}
Here's a stackblitz 演示服务及其用法。