【问题标题】:Ionic 3 - Show JSON response from HTTP request in formatted wayIonic 3 - 以格式化方式显示来自 HTTP 请求的 JSON 响应
【发布时间】:2018-07-24 13:22:27
【问题描述】:

我的 Ionic 3 应用程序向 Rails 后端发出 HTTP 请求。如果请求成功,应用程序会执行它必须做的任何事情,当出现错误时,API 会返回 HTTP 错误代码和 JSON 错误消息。

我希望我的应用以一种对用户很好的方式显示带有错误消息的警报,而不是 JSON。

error => {
  let alert = this.alertCtrl.create({
  title: 'Algo não deu certo...',
  subTitle: error.text(),
  buttons: ['OK']
});

这会导致:

我想对其进行格式化。我知道我可以遍历这些项目并显示它们,但我想知道是否有更简单的方法/更少的代码来做到这一点。

【问题讨论】:

  • 嗨@almo你能提供你在错误数据中的内容吗?

标签: angular ionic-framework


【解决方案1】:

如果我理解得很好,你需要这样的东西:

const error = {
  "from": ["can't be blank"],
  "to": ["can't be blank"],
  "passenger": ["must exist"],
};

const errorMessage = Object.keys(error).reduce((acc, cur) => `${acc} ${cur} ${error[cur]}`, '').slice(1);

console.log(errorMessage);

这是Array#Reduce 的基本示例。

这是另一个带有格式化文本的示例:

const error = {
  "from": ["can't be blank"],
  "to": ["can't be blank"],
  "passenger": ["must exist"],
};

const errorMessage = Object.keys(error).reduce((acc, cur) => `${acc} ${cur.charAt(0).toUpperCase()}${cur.slice(1)}: ${error[cur]}!`, "").slice(1);

console.log(errorMessage);

【讨论】:

    【解决方案2】:

    因为只有在返回错误时才会执行错误,所以你可以像这样以文本形式给出错误消息:

    error => {
    let alert = this.alertCtrl.create({
    title: 'Algo não deu certo...',
    subTitle: 'Your error Message',
    buttons: ['OK']
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 2013-10-13
      相关资源
      最近更新 更多