简体   繁体   English

如何在第二个请求中使用来自concatMap的第一个响应

[英]How to use the first response from concatMap in the second request

I am trying to avoid the nested subscription in request to the backend. 我试图避免在对后端的请求中嵌套订阅。 I need to login, then get a service token based on the response of the login, then get a encryption token based on the service token. 我需要登录,然后根据登录的响应获取服务令牌,然后根据服务令牌获取加密令牌。

I have seen about concatMap but i am not sure how to use the first response in the second request or third 我已经了解了concatMap,但是我不确定如何在第二个请求或第三个请求中使用第一个响应

  this.rest.CallLogin(this.data).pipe(
            concatMap(serviceToken => this.rest.GetServiceTicket(1stresponse.headers.get('Location'))),// dont know how to get the 1st response from CallLogin
            concatMap(tokenResponse => this.rest.getEncryptToken(serviceToken)),

        );

You can use flatMap in place of the nested subscriptions. 您可以使用flatMap代替嵌套订阅。

import { flatMap } from 'rxjs/operators';

this.rest.CallLogin(this.data).pipe(
        flatMap((serviceToken) => {
            //serviceToken is the response of first call
            return this.rest.GetServiceTicket(serviceToken.headers.get('Location'))
        }),
        map((tokenResponse) => {
            //tokenResponse is the response of second call
            this.rest.getEncryptToken(tokenResponse)
        });

If i understood correctly then you only want to chain the calls and use the response header from the first response. 如果我理解正确,那么您只想链接呼叫并使用第一个响应中的响应头。 For that you need to use observe on response in your first call: 为此,您需要在第一个电话中使用观察响应:

this.rest.CallLogin(this.data, {observe: 'response'}).pipe(
    concatMap(loginResponse => this.rest.GetServiceTicket(loginResponse.headers.get('Location'))),
    concatMap(serviceTicket => this.rest.getEncryptToken(serviceTicket)),
);

I ended up using SwitchMap 我最终使用了SwitchMap

 this.rest.CallLogin(this.data).pipe(
        switchMap((response: any) => {
        this.data.requestUrl = response.headers.get('Location');
        return this.rest.GetServiceTicket(this.data) // serviceticket
        }),
        switchMap((serviceticket) => {
            return this.rest.getEncryptToken(serviceticket.body) // tokenResponse
        }),
        //continue doing requests or stuff
        switchMap((tokenResponse) => {
            encryptToken = tokenResponse;
            ///...                
        }),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM