In this angular 2 application multiple HTTP requests can be fired at the same time. These are fired from instances of the same component but a number of these components can be displayed on a page at one time.
The server requires the retrieval of a token before it gives out data. Now whenever for example 6 requests are fired at the same time a check is executed for each to see if the token is valid. If it is invalid however they don't wait for the response of the first request and use that token for the other requests.
I am using mergeMap to make sure that the request for data gets executed after the token is retrieved, which makes the application functional. However i'd like it not to retrieve multiple tokens when requests are fired at the same time.
I have been trying numerous things but I can't seem to find a solution that works for my scenario. I'd appreciate any assistance you might be able to give. See some of the code I tried below.
Get
Get = (path: string): any => {
if (this.authentication.isAuthenticated()) {
this.SetAuthorizationHeader(this.authentication.token);
return this.GetRequest(path);
} else {
return this.authentication.getToken()
.mergeMap(prop => {
this.authentication.setToken(prop);
this.SetAuthorizationHeader(this.authentication.token);
return this.GetRequest(path);
});
}
}
getToken
getToken(): Observable<Response> {
if (!this.requestInProgress) {
this.requestInProgress = true;
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('client_id', Constants.CLIENT_ID);
urlSearchParams.append('grant_type', Constants.GRANT_TYPE);
let body = urlSearchParams.toString()
this.pendingRequest = this.http.post(`${this.configuration.BaseUrl}`, body, { headers: this.configuration.Headers })
.map(this.extractData)
}
return this.pendingRequest;
}