0

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

我见过 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)),

        );
4

3 回答 3

0

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

this.rest.CallLogin(this.data, {observe: 'response'}).pipe(
    concatMap(loginResponse => this.rest.GetServiceTicket(loginResponse.headers.get('Location'))),
    concatMap(serviceTicket => this.rest.getEncryptToken(serviceTicket)),
);
于 2019-08-01T07:27:18.273 回答
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)
        });
于 2019-08-01T07:05:55.297 回答
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;
            ///...                
        }),
于 2019-08-17T00:57:54.213 回答