如何在第二个请求中使用来自 concatMap 的第一个响应
How to use the first response from concatMap in the second request
我试图避免嵌套订阅请求到后端。我需要登录,然后根据登录的响应获取服务令牌,然后根据服务令牌获取加密令牌。
我看过有关 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)),
);
您可以使用 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)
});
如果我理解正确,那么您只想链接调用并使用第一个响应中的响应 header。为此,您需要在第一次调用时使用 observe on response:
this.rest.CallLogin(this.data, {observe: 'response'}).pipe(
concatMap(loginResponse => this.rest.GetServiceTicket(loginResponse.headers.get('Location'))),
concatMap(serviceTicket => this.rest.getEncryptToken(serviceTicket)),
);
我最终使用了 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;
///...
}),
我试图避免嵌套订阅请求到后端。我需要登录,然后根据登录的响应获取服务令牌,然后根据服务令牌获取加密令牌。
我看过有关 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)),
);
您可以使用 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)
});
如果我理解正确,那么您只想链接调用并使用第一个响应中的响应 header。为此,您需要在第一次调用时使用 observe on response:
this.rest.CallLogin(this.data, {observe: 'response'}).pipe(
concatMap(loginResponse => this.rest.GetServiceTicket(loginResponse.headers.get('Location'))),
concatMap(serviceTicket => this.rest.getEncryptToken(serviceTicket)),
);
我最终使用了 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;
///...
}),