As someone who is new to Angular 2, I found that things were much simpler with interceptors in version 1.*. All you had to do was add them and suddenly your headers were available everywhere, making it easy to handle requests especially when dealing with invalid tokens.
In my Angular 2 project, I am utilizing RxJs to manage my token:
getToken(login: string, pwd: string): Observable<boolean> {
let bodyParams = {
grant_type: 'password',
client_id: 'admin',
scope: AppConst.CLIENT_SCOPE,
username: login,
password: pwd
};
let params = new URLSearchParams();
for (let key in bodyParams) {
params.set(key, bodyParams[key])
}
let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({headers: headers});
return this.http.post(AppConst.IDENTITY_BASE_URI + '/connect/token', params.toString(), options)
.map((response: Response) => {
let data = response.json();
if (data) {
this.data = data;
localStorage.setItem('auth', JSON.stringify({
access_token: data.access_token,
refresh_token: data.refresh_token
}));
return true;
} else {
return false;
}
});
}
Now, the challenge lies in how I can seamlessly use this token in all my requests without having to manually set the header each time. This practice is not ideal.
If any request returns a 401
-error, how can I intercept it, obtain a new token, and then resume all requests just like we used to in Angular 1?
I attempted to work with JWT from this source jwt, but unfortunately, it didn't meet my requirements. In Angular 1, I was using Restangular and everything worked smoothly there, even when handling tokens manually as outlined here: https://github.com/mgonto/restangular#seterrorinterceptor.