【问题标题】:How retrive a value from JSON object sent by server in Ionic 3如何从 Ionic 3 中服务器发送的 JSON 对象中检索值
【发布时间】:2018-07-10 08:46:45
【问题描述】:

所以基本上我是在向服务器请求一个 post 请求,作为回报,以这种形式在 JSON 对象中发送一个令牌:

{
   token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIyLCJpc3MiOiJodHRwczovL2hvYnVkZGllcy5jb20vYXBpL2F1dGgvbG9naW5fYXBpIiwiaWF0IjoxNTE3MzkwNTkwLCJleHAiOjE1MTczOTQxOTAsIm5iZiI6MTUxNzM5MDU5MCwianRpIjoiWUxtdXJ5TkV2UzlwSEExTyJ9.nWV7OWLYdMJmZCHNP9tFuAmZ84DwzYO00O3jQ_RfhXQ"
}

我需要的是将该令牌附加到 apiUrl 以获取当前登录用户的适当信息。 服务器在变量“result”中返回这个 JSON 对象,如下所示:

// 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) => {
    //storing the returned Token from the server.
    var login_token = result;
    //storing the retured Token into Ionic Storage.
    this.storage.set("tokenn", result);
    console.log(result);
    console.log('success');
    //if successful, then set the rootPage to TabsPage
    this.navCtrl.setRoot(TabsPage);
  }, (err) => {
    console.log(err);
  });

但是当我附加结果时,存储在存储中,它附加了返回的对象,这里我只需要字符串。

我只需要这个:

“eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIyLCJpc3MiOiJodHRwczovL2hvYnVkZGllcy5jb20vYXBpL2F1dGgvbG9naW5fYXBpIiwiaWF0IjoxNTE3MzkwNTkwLCJleHAiOjE1MTczOTQxOTAsIm5iZiI6MTUxNzM5MDU5MCwianRpIjoiWUxtdXJ5TkV2UzlwSEExTyJ9.nWV7OWLYdMJmZCHNP9tFuAmZ84DwzYO00O3jQ_RfhXQ” EM> 强>

那么,如何从我的 Ionic 应用程序中的对象中提取该字符串。

【问题讨论】:

  • 我认为你必须做 result['token']

标签: angularjs json ionic-framework ionic2 ionic3


【解决方案1】:

您要做的是将整个 JSON 即从服务器返回的结果存储在变量“tokenn”中。

尝试将结果中的标记映射到仅存储字符串部分。

//storing the retured Token into Ionic Storage.
this.storage.set("tokenn", result['token']);
console.log(result);

【讨论】:

    【解决方案2】:

    很简单:

    let loginToken = JSON.parse(result).token; console.log(loginToken); //Will print exactly what you need 然后您可以将登录令牌存储在存储中。

    基本上使用 JSON.parse,您可以将 JSON 转换为对象

    【讨论】:

      【解决方案3】:

      因为您将整个对象存储在存储中。 你可以通过两种方式解决这个问题 1.您仅将字符串存储到存储并访问它。

      this.storage.set("tokenn", result.token);
      const result = this.storage.get("tokenn");
      console.log(result);
      1. 存储整个 JSON 并仅访问字符串

      this.storage.set("tokenn", result);
      const result = this.storage.get("tokenn");
      console.log(result.token);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-07
        • 2018-08-31
        • 1970-01-01
        • 1970-01-01
        • 2021-04-23
        • 1970-01-01
        相关资源
        最近更新 更多