I am trying to create a Ionic v3 app able to consume REST APIs using an api token as logging method.
After the user performs the login, the variable currentUser gets set and from now then the AuthInterceptor will always send the api token attached to all requests.
However, apparently the currentUser is always null even though the alert in the login, used as a check, always shows the correct user first name.
AuthInterceptor.ts
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
currentUser: any;
constructor(public storage: Storage) {
this.storage.get('currentUser').then((val) => {
this.currentUser = JSON.parse(val);
});
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with api token if available
console.log(this.currentUser);
if (this.currentUser && this.currentUser.api_token) {
request = request.clone({
setHeaders: {
'Authorization': `Bearer ${this.currentUser.api_token}`
}
});
}
return next.handle(request);
}
}
AuthSvc.ts
login(email: string, password: string) {
return this.http.post<any>('login', { email: email, password: password })
.map(data => {
// login successful if there's an api token in the response
if (data.user && data.user.api_token) {
this.setUser(data.user);
return data.user;
}
});
}
setUser(user) {
console.log('setUser');
// store user details and the token in local storage to keep user logged in between page refreshes
this.storage.set("currentUser", JSON.stringify(user));
}
login.ts (page)
this.authSvc.login(this.user.email, this.user.password)
.subscribe(
data => {
alert('Hi '+data.name);
this.navCtrl.setRoot(HomePage);
},
error => {
});
The API returns a JSON object consisting of
{
"success": true,
"user": User obj
}