Concatenation of Angular http requests

怎甘沉沦 提交于 2019-12-07 19:41:31

问题


I am facing the following scenario. There is a Front End app, built with Angular(2), which is connected with a REST Back End accessible via http. Once an user logs in (using email and pwd), the Back End returns data related to the user and in particular an id associated with the user (let's call this userId) and the code of the region where he lives (let's call this regionId). Via the userId I can query the Back End to get the affinity group ID to which the user belongs (let's call this affinityId). Finally, using affinityId and regionId I can retrieve from the Back End the discount to apply to the user.

In other words, the Back End offers 3 APIs:

  • getUserData(email: string, pwd: string) : returns all user data including userId and regionId
  • getAffinityPerUser(userId: number) : returns a number representing the affinityId
  • getDiscount(regionId: number, affinityId: number) : returns a number representing the discount

If I access these APIs via Angular http client I can build the following APIs (in a sort of Javascript pseudo code)

  • getUserData(email: string, pwd: string) : Observable(<{userId, regionId, ...}>)
  • getAffinityPerUser(userId: number) : Observable()
  • getDiscount(regionId: number, affinityId: number) : Observable()

I would like to know if I can combine such Observables using the RxJs operators to obtain the discount info which I am looking for.

I can concatenate the first 2 APIs via switchMap to get the affinityId with something like

this.getUserData(email, pwd)
     .switchMap(userData => this.getAffinityPerUser(userData.userId))

but then I do not know how to combine the affinityId Observable (returned by getAffinityPerUser) with the userData Observable (returned by getUserData) to be able to have both affinityId and regionId which I need to call the getDiscount API.

Any help is very much appreciated


回答1:


You can combine all your operations like this :

this.getUserData(email, pwd)
     .switchMap(userData => this.getAffinityPerUser(userData.userId)
                                .map(affinity => [affinity, userData.regionId])) // return a tuple combining required elements
     .switchMap(([affinity, regiondId) => this.getDiscount(regionId, affinity)) // use destructuration to extract the 2 elements of the tuple


来源:https://stackoverflow.com/questions/41702140/concatenation-of-angular-http-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!