在我的身份验证服务中,我需要存储经过身份验证的用户的 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 storedexport const USERNAME_KEY = 'username_key'; // this is storedexport 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); }));}
1 回答

喵喵时光机
TA贡献1846条经验 获得超7个赞
如果
this.user = this.helper.decodeToken(res['access']);
在 this.user 中设置此数据
{token_type: "access", exp: 123 , user_id: 13}
您可以使用 user_id 属性 com this.user,而不是来自 res
this.user = this.helper.decodeToken(res['access']);
this.storage.set(USER_ID, this.user['user_id']);
添加回答
举报
0/150
提交
取消