【问题标题】:How to address the response data correctly?如何正确处理响应数据?
【发布时间】:2020-03-07 12:29:07
【问题描述】:

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

【问题讨论】:

  • 如果你 console.log(res) 它输出什么?似乎他们的响应没有“user_id”属性。

标签: javascript json angular typescript ionic-framework


【解决方案1】:

如果

this.user = this.helper.decodeToken(res['access']);

在 this.user 中设置此数据

{token_type: "access", exp: 123 , user_id: 13}

你可以使用 com this.user 的 user_id 属性,而不是来自 res

this.user = this.helper.decodeToken(res['access']);
this.storage.set(USER_ID, this.user['user_id']);

【讨论】:

    猜你喜欢
    • 2015-02-27
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2013-08-18
    • 2021-03-23
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多