如何正确处理响应数据?

在我的身份验证服务中,我需要存储经过身份验证的用户的 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);

        }));

}



慕婉清6462132
浏览 187回答 1
1回答

喵喵时光机

如果this.user = this.helper.decodeToken(res['access']);在 this.user 中设置此数据{token_type: "access", exp: 123 , user_id: 13}您可以使用 user_id 属性 com this.user,而不是来自 resthis.user = this.helper.decodeToken(res['access']);this.storage.set(USER_ID, this.user['user_id']);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript