Reputation: 1062
In my authentication service, I need to store the id of the authenticated user. I also need to store the access token and the username. Both (token and username) are stored correctly(Key and Value) in the storage when I go to the application tab of my dev tool. But my user_id is either the value undefined when using this code this.storage.set(USER_ID, res['user_id']);
or I get as a value NaN
when I first try to convert it into a number(which is probably necessary since user_id is a number). This would be this version this.storage.set(USER_ID, this.validateId(res['user_id']));
For console.log('my user: ', this.user);
I get this data: my user: {token_type: "access", exp: 123 , user_id: 13}
What am I doing wrong? Since the user_id is a number it should work!
const TOKEN_KEY = 'access_token'; // this is stored
export const USERNAME_KEY = 'username_key'; // this is stored
export const USER_ID = 'user_id'; // this isn't stored
...
user = null;
authenticationState = new BehaviorSubject(false);
constructor(private http: HttpClient, private alertCtrl: AlertController, private storage: Storage, private helper: JwtHelperService,
private plt: Platform) {
this.plt.ready().then(() => {
this.checkToken();
});
}
checkToken() {
this.storage.get(TOKEN_KEY).then(access => {
if (access) {
this.user = this.helper.decodeToken(access);
this.authenticationState.next(true);
}
});
}
validateId(user_id: any): number {
return parseInt(user_id);
}
apilogin(username: string, password: string) {
return this.http.post<any>(`http://127.0.0.1:8000/api/token/`, { username, password })
.pipe(
tap(res => {
this.storage.set(TOKEN_KEY, res['access']); // this is stored
this.storage.set(USERNAME_KEY, username); // this is stored
this.storage.set(USER_ID, this.validateId(res['user_id'])); // this isn't stored
this.user = this.helper.decodeToken(res['access']);
console.log('my user: ', this.user);
this.authenticationState.next(true);
}),
catchError(e => {
this.showAlert('Oops smth went wrong!');
throw new Error(e);
}));
}
Upvotes: 0
Views: 69
Reputation: 8065
If
this.user = this.helper.decodeToken(res['access']);
set this data in this.user
{token_type: "access", exp: 123 , user_id: 13}
You can use user_id attribute com this.user, not from res
this.user = this.helper.decodeToken(res['access']);
this.storage.set(USER_ID, this.user['user_id']);
Upvotes: 1