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
相关产品推荐
相关产品推荐

