*ngFor 在 <li> 中使用 Angular 版本 8.2.8 绑定从 API 接收的数据,但无法显示数据

Posted

技术标签:

【中文标题】*ngFor 在 <li> 中使用 Angular 版本 8.2.8 绑定从 API 接收的数据,但无法显示数据【英文标题】:*ngFor used in <li> to bind the data received from API using angular version of 8.2.8,but could not display the data 【发布时间】:2020-02-06 01:04:28 【问题描述】:

我想使用 8.2.8 版的 angular js 从 API 显示用户标题,并尝试使用 *ngFor 将其绑定在 &lt;ul&gt;&lt;li&gt; 中。通过将 json 值转换为数组格式后此代码如下所示

search.component.ts :

getUsers()
  
    this.githubservice.getUser(this.SearchText);
    this.SearchResult = this.githubservice.getUser(this.SearchText).subscribe(
      res => 
        res.json;
      
    );
    this.SearchResult = Array.of(this.SearchResult);

  

json 数据将按以下格式接收:

[
  
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  ,
  
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  
]

search.component.html :(尝试绑定存储在变量SearchResult中的json数据)

<span><input type="text" (keyup)="onKeyup($event)" /></span>
<span><input type="button" (click)="getUsers()" value="Search" /></span>
<p>SearchResult.title</p>
<ul>
  <li *ngFor="let user of SearchResult">SearchResult.title</li>
</ul>

【问题讨论】:

您可能需要更好地阅读文档并学习 ngFor 和 ngIf @AbhishekKothari 这里是有关结构指令的文档的直接链接:angular.io/guide/structural-directives,但我怀疑只是浏览 tutorial 会提供很多必要的信息。 @robsiemb 至少这个家伙会知道 *ngFor 是 for 循环, *ngIf 是 for 条件。他连那部分都弄错了 @robsiemb,Abhishek Kothari,我在编辑后分享了代码 sn-p,请帮助我了解如何在 html (search.component.html) 中绑定数据 在循环内部,您需要引用“用户”而不是“搜索结果”。请参阅我的答案中的示例。 【参考方案1】:

请参阅 this example from the heros tutorial 和 this more complete documentation。

您已将循环放置在 ngIf 指令中,但它属于 ngFor。 ngIf 应该只在需要时测试布尔条件。

对于循环本身,您需要如下所示:

<ol>
<li *ngFor="let user of SearchResult"> user.login </li>
</ol>

您不能只将字段名称放在 ngFor 中。

如果这不能回答问题,请提供minimal, reproducable example,包括上下文中的代码。

【讨论】:

我有来自 API 的数据,例如“api.github.com/search/users?q=js”,因此将其存储在声明为 public 的变量 SearchResult 中,代码如下 this.SearchResult = this.githubservice.getUser(js ).subscribe (res => console.log(res); this.SearchResult = res; ); @selvaan 并请阅读有关最小可重现示例中所涉及内容的链接——只是数据还不够,它还需要可以运行的代码来证明您遇到的问题。如果上面的答案不能解决它,这可能会在没有 API 的情况下重现。

以上是关于*ngFor 在 <li> 中使用 Angular 版本 8.2.8 绑定从 API 接收的数据,但无法显示数据的主要内容,如果未能解决你的问题,请参考以下文章

[Angular 2] *ngFor with index

在 ngFor 中动态分配元素 id

作用域变量的实现如何在 *ngFor 中工作

ngFor 将索引作为属性中的值

如何为非 li 元素申请 ngfor?

在 ngFor angular 2 中提供活动类 onclick