[英]Angular 2 - What to do when an Http request depends on result of another Http request
I'm having trouble figuring out how to use the result of an Http request to make another Http request. 我无法弄清楚如何使用Http请求的结果来发出另一个Http请求。
I have a Service that requests and receives JSON Web Tokens from a backend API that looks like: 我有一个服务,它从后端API请求和接收JSON Web令牌,如下所示:
@Injectable()
export class JwtAuthorizationService {
constructor(private http: Http) {}
public requestToken(): Observable<string> {
// Set dummy credentials.
let body = this.setBody();
let headers = this.setHeaders();
let token = this.http.post(tokenUrl, body, { headers: headers })
.map(this.extractData)
.catch(this.handleError);
// Return the Observable
return token;
}
private extractData(res: Response): string {
let body = res.text();
return body || "";
}
How can I now use the result of the requestToken()
(an Observable) to make an another API call, authenticated with the JWT, and get the result back from that? 我现在如何使用
requestToken()
(一个Observable)的结果进行另一个API调用,使用JWT进行身份验证,并从中获取结果? Or maybe more simply, what do you do when one Http call depends on the result of another? 或者更简单地说,当一个Http调用依赖于另一个Http调用的结果时,你会怎么做?
You could use the flatMap
operator to do that: 您可以使用
flatMap
运算符来执行此操作:
this.authorizationService.requestToken().flatMap(token => {
var headers = new Headers();
headers.append('Authorization', `Bearer ${token}`);
return this.http.get('...', { headers }).map(res => res.json());
});
What you could also do is to make this transparent by extending the HTTP class. 您还可以做的是通过扩展HTTP类使其透明。 In it, you could check the token validity and if it's expired, call the
requestToken
method. 在其中,您可以检查令牌有效性,如果它已过期,请调用
requestToken
方法。
See this question for more details: 有关详细信息,请参阅此问题:
You can for example use the switchMap
operator if you have a network call that needs to use the result of a previous network call: 例如,如果您的网络呼叫需要使用先前网络呼叫的结果,则可以使用
switchMap
运营商:
const combined$ = jwtAuthenticationService.requestToken()
.switchMap(tokenBody => this.http.get('/someurl') );
This is the marble diagram: 这是大理石图:
// requestToken
|---------------T---|
// second HTTP request
|------R--|
// combined$
|--------------------------R--|
The sequence goes like this: 顺序如下:
combined$
would have unsubscribed from it combined$
将取消订阅 combined$
completes combined$
完成
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.