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

时间:2019-08-01 03:23:36

标签: angular nested observable concatmap

我正在尝试避免在对后端的请求中嵌套订阅。我需要登录,然后根据登录的响应获取服务令牌,然后根据服务令牌获取加密令牌。

我看过有关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)),

        );

3 个答案:

答案 0 :(得分:0)

您可以使用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)
        });

答案 1 :(得分:0)

如果我正确理解,那么您只想链接呼叫并使用第一个响应中的响应头。为此,您需要在第一个呼叫中使用观察响应:

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

答案 2 :(得分:0)

我最终使用了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;
            ///...                
        }),