Reputation: 7561
I'm using Restangular in my Angular 5 project. In addErrorInterceptor section, if you look at the code it calls the refreshAccesstoken
method and then gets the new access token in switchMap
part. By now I'm returning a replySubject
in my refreshAccesstoken
method so if I subscribe to the return value, I can get the new access token but I'm not able to get it in switchMap as I don't know what it is (I've also searched for switchMap but I just found some functions which didn't help me).
Here is my code for AuthService.refreshAccessToken:
refreshAccessToken() {
let resultSubject: ReplaySubject<any> = new ReplaySubject<any>();
const url = this.AUTH_URL + 'oauth/token';
const requestOptions = {
headers: new Headers({
authorization: 'Basic ' + btoa(this.clientId + ':' + this.clientSecret),
'Content-Type': 'application/x-www-form-urlencoded'
})
};
const body = {
grant_type: 'refresh_token',
refresh_token: this.refreshToken,
// scope: ''
};
let params = this.utilityService.convertObjectToURLParams(body);
this._http.post(url, params.toString(), requestOptions).subscribe(
response => {
let result = response.json();
// console.log('refreshed_access_token', result);
this.accessToken = result.access_token
this.refreshToken = result.refresh_token
this.expireIn = result.expire_in
resultSubject.next(this.accessToken);
},
error => {
resultSubject.error(error);
}
);
return resultSubject;
}
Upvotes: 0
Views: 289
Reputation: 17762
Why do you need to use a ReplySubject? It seems you are using it just to emit the new access token.
If this is the case, and if I do not miss something, then you could reach the same result in a simpler way, like
refreshAccessToken() {
const url = this.AUTH_URL + 'oauth/token';
const requestOptions = {
headers: new Headers({
authorization: 'Basic ' + btoa(this.clientId + ':' + this.clientSecret),
'Content-Type': 'application/x-www-form-urlencoded'
})
};
const body = {
grant_type: 'refresh_token',
refresh_token: this.refreshToken,
// scope: ''
};
let params = this.utilityService.convertObjectToURLParams(body);
this._http.post(url, params.toString(), requestOptions).map(
response => {
let result = response.json();
// console.log('refreshed_access_token', result);
this.accessToken = result.access_token
this.refreshToken = result.refresh_token
this.expireIn = result.expire_in
return this.accessToken;
}
);
}
Basically you just substitute subscribe
with map
and then it should work
Upvotes: 2