You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic 3中如何从服务器返回的JSON对象提取Token字符串

在Ionic应用中提取登录返回的Token字符串

很简单,因为服务器返回给你的是一个包含token属性的JSON对象,你只需要直接访问这个属性就能提取出Token字符串啦。

修改步骤:

  • 当你从this.restProvider.loginUser(data)拿到result后,不要直接把整个对象存起来,而是通过result.token获取到具体的Token字符串。
  • 把存储到Ionic Storage的代码也改成存储这个字符串,而不是整个对象。

修改后的代码示例:

// for login the user in the app.
loginUser() {
 //values from the login form
 var data = { email: this.emailVar, password: this.passwordVar }
 //calling the loginUser method from the Provider: Test.ts
 this.restProvider.loginUser(data)
 .then((result) => {
 // 提取Token字符串
 var login_token = result.token;
 // 将Token字符串存入Ionic Storage
 this.storage.set("tokenn", login_token);
 console.log('提取到的Token:', login_token);
 console.log('登录成功');
 //if successful, then set the rootPage to TabsPage
 this.navCtrl.setRoot(TabsPage);
 }, (err) => {
 console.log(err);
 });
}

补充说明(可选):

如果你的TypeScript有类型检查报错,你可以给result定义一个接口来明确返回结构,避免类型歧义:

interface LoginResponse {
  token: string;
}

// 然后在then回调里指定类型
.then((result: LoginResponse) => {
  var login_token = result.token;
  // ... 后续逻辑代码
})

这样就能确保你正确获取到Token字符串,之后就可以把它和apiUrl拼接,用来请求当前登录用户的信息啦。

内容的提问来源于stack exchange,提问作者Osama Riaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:38:38