在我的身份验证服务中,我需要存储经过身份验证的用户的 ID。我还需要存储访问令牌和用户名。当我转到我的开发工具的应用程序选项卡时,(令牌和用户名)都正确存储在存储中(键和值)。但是我的 user_id 要么是使用此代码时未定义的值,要么是我第一次尝试将其转换为数字时this.storage.set(USER_ID, res['user_id']);得到的值NaN(这可能是必要的,因为 user_id 是一个数字)。这将是这个版本this.storage.set(USER_ID, this.validateId(res['user_id'])); 因为console.log('my user: ', this.user);我得到了这个数据:my user: {token_type: "access", exp: 123 , user_id: 13}
我究竟做错了什么?由于 user_id 是一个数字,它应该可以工作!
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);
}));
}
喵喵时光机
相关分类