【问题标题】:fetching and displaying the backend json in an Angular/Ionic project在 Angular/Ionic 项目中获取和显示后端 json
【发布时间】:2020-08-23 15:08:05
【问题描述】:

我在一个带有 Angular 框架的 ionic 项目中工作,我的要求是通过 api 调用获取后端 json 数据并在 HTML 页面中读取 JSON 数据。

下面是我试过的代码

代理 api 调用:

http://example.com/broker/get-user-names

后端Json数据:

 [

  {
"USER_NAME": "John",
"USER_COUNTRY": "USA"
},


 {
"USER_NAME": "Smith",
"USER_COUNTRY": "Canada"
 },


{
 "USER_NAME": "Peter",
"USER_COUNTRY": "Russia"
 }

 ]

在 .ts 页面中:定义了一个数组来保存来自 API 的数据

userNames = [];

(创建了一个serive.ts并在那里定义了api url),编写的函数如下;

   getUserNames() {
    this.apiService.getUserNames(this.apiService.loggedInUser.value.id)
     .then(res => {
     this.userNames= JSON.parse(res); 
  },
  err => {
    alert(err);
  }
)
 }

现在当尝试在 HTML 页面中显示内容时,它没有显示任何内容

<p *ngFor="let user of userNames">{{user.USER_NAME}} </p>

这不起作用。我不明白我哪里出错了,请帮助我。

谢谢。

【问题讨论】:

  • 你得到正确的响应还是控制台有错误??
  • 应该是

    {{user.USER_NAME}}

    而不是

    *ngFor="let user of userNames">{ {user.USER_NAME}}

  • 抱歉,我刚刚编辑了问题,即使使用了这个

    {{user.USER_NAME}}

    。它不工作
  • 能在Json.parse之后显示userNames的console.log吗?
  • 它没有显示任何东西,我什至添加了一个像这样的警报 alert(JSON.stringify(this.userNames));但它也没有显示

标签: html json angular api ionic-framework


【解决方案1】:

如果用户名填写正确:

应该是

<p *ngFor="let user of userNames">{{user.USER_NAME}} </p>

而不是

<p>*ngFor="let user of userNames">{{user.USER_NAME}} </p>

【讨论】:

  • 抱歉,我刚刚编辑了这个问题,即使使用了这个

    {{user.USER_NAME}}

    。它不工作
  • 应该有空格

  • 它没有显示任何东西,我什至添加了一个像这样的警报 alert(JSON.stringify(this.userNames));但它也没有显示
猜你喜欢
  • 2020-06-23
  • 2021-08-27
  • 2020-12-21
  • 1970-01-01
  • 2020-11-05
  • 2017-12-06
  • 2016-08-04
  • 2021-01-09
  • 2019-02-19
相关资源
最近更新 更多