【问题标题】:Angular2 Iterate Over Array of Objects Using *ngForAngular2 使用 *ngFor 迭代对象数组
【发布时间】:2017-08-03 20:10:37
【问题描述】:

我有一个 Angular2 组件,它使用 Angular 的 http 服务来调用 API 端点,该端点返回一个 json 格式的响应。响应是一个对象数组,每个对象包含两个字符串值。

我正在尝试使用*ngFor="let cluster of apiClusters" 对它们进行迭代,当呈现此<h1>{{ cluster }}</h1> 时,我得到[object Object]。对我来说,这很有意义,因为我没有使用点或括号表示法来访问键的值。

但是,当我尝试使用点或括号表示法 {{ cluster.ClusterName }} 时,不会呈现任何内容。这不是您应该访问这些值的方式吗?

另一个similar post 表示有同样的问题,但据我所知,他们的问题是他们试图迭代匿名对象的对象。虽然,当对象包含在数组中时,该问题的公认答案使用点符号来访问其中一个键的值。

这让我认为这可能是 Angular 组件中的代码有问题,但我无法确定它是什么。

ASP.NET Core Web API 控制器:

[HttpGet]
    public IActionResult Get()
    {

        var clusterData = new[] 
        {
            new { ClusterName = "Agriculture, Food, and Natural Resources", ClusterDescription = "hello" },
            new { ClusterName = "Architecture and Construction", ClusterDescription = "hi" },
            new { ClusterName = "Arts, Audio/Video Technology, and Communications", ClusterDescription = "tbd" },
            new { ClusterName = "Business, Management, and Administration", ClusterDescription = "tbd" },
            new { ClusterName = "Education and Training", ClusterDescription = "tbd" },
            new { ClusterName = "Finance", ClusterDescription = "tbd" },
            new { ClusterName = "Government and Public Administration", ClusterDescription = "tbd" },
            new { ClusterName = "Health Science", ClusterDescription = "tbd" },
            new { ClusterName = "Hospitality and Tourism", ClusterDescription = "tbd" },
            new { ClusterName = "Human Services", ClusterDescription = "tbd" },
            new { ClusterName = "Information Technology", ClusterDescription = "tbd" },
            new { ClusterName = "Law, Public Safety, Corrections, and Security", ClusterDescription = "tbd" },
            new { ClusterName = "Manufacturing", ClusterDescription = "tbd" },
            new { ClusterName = "Marketing, Sales, and Service", ClusterDescription = "tbd" },
            new { ClusterName = "Science, Technology, Engineering, and Mathematics", ClusterDescription = "tbd" },
            new { ClusterName = "Transportation, Distribution, and Logistics", ClusterDescription = "tbd" }
        };

        return new JsonResult
        (
            clusterData
        );

    }

Angular2 组件:

import { Component, OnInit, PipeTransform, Pipe } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']

})

export class AppComponent implements OnInit {

    constructor(private _httpService: Http) { }

    apiClusters: { ClusterName: string, ClusterDescription: string }[] = [];

    ngOnInit() {
        this._httpService.get('/api/clusters').subscribe(values => {
            this.apiClusters = values.json() as { ClusterName: string, 
            ClusterDescription: string }[];
        });
    }

}

HTML 组件模板

 <!-- Career Cluster Component -->
<main class="container justify-content-center mt-5 mb-5 flex-grow w-75">
  <div *ngFor="let cluster of apiClusters">
    <a href="#">
      <div class="card">
        <div class="header" id="bg-img"></div>
          <div class="content">
            <h1>{{ cluster.ClusterName }}</h1>
            <p class="cluster-description">
              Blurp about industry cluster. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin bibendum nisi sed efficitur scelerisque. Nullam sollicitudin ultricies maximus. Vestibulum eu molestie dui, eu lacinia turpis. Pellentesque rutrum
              magna ac risus.
            </p>
          </div>
        </div>
      </a>
    </div>
  </main>
  <!-- Career Cluster Component End-->

【问题讨论】:

  • 将您的数据记录到控制台,看看它实际包含什么
  • 首先,试试&lt;h1&gt;{{ cluster | json }}&lt;/h1&gt;,看看你得到了什么。根据 ASP.NET 的设置方式,情况可能会发生变化。所以它可能需要使用{{ cluster.clusterName }}(小写'c')
  • 您可能需要使用map() 从 API 返回返回的 JSON 的内部值。实际数据可能类似于values.clusterData
  • @DeborahK 是正确的。这种情况必须随着 ASP.Net 的设置方式而改变。运行 &lt;h1&gt;{{ cluster | json }}&lt;/h1&gt; 会显示大小写的变化,将其记录到控制台也是如此。
  • 好的,我将其移至答案。

标签: angular angular2-template asp.net-core-webapi


【解决方案1】:

首先,试试

<h1>{{ cluster | json }}</h1> 

看看你得到了什么。

根据 ASP.NET 的设置方式,情况可能会发生变化。所以它可能需要使用

{{ cluster.clusterName }}

(小写“c”)

【讨论】:

    【解决方案2】:

    我没有看到任何明显的错误,因此您的调试技能需要发挥作用。

    1. 检查浏览器中的网络选项卡,确保呼叫返回的正是您所期望的。
    2. 在模板底部添加 &lt;pre&gt;{{ apiClusters | json }}&lt;/pre&gt; 以查看您设置的返回值的 javascript 表示
    3. 在您的循环中,使用 {{ cluster | json }} 对数组中的每个值执行相同操作
    4. 在您的组件构造函数中使用window['C'] = this,您可以检查这些值并在控制台中使用它们来查看发生了什么。如果您想在更改值后查看模板中的更改,则必须在更改某些内容后注入 ApplicationRef 并调用 tick(),或者通过在您的应用中执行某些操作来触发更改检测。
    5. 注释掉您的 api 调用并将数据手动设置为您期望的数据以验证其是否正常工作(即this.apiClusters = [{ClusterName:'name',ClusterDescription:'desc'}];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 2017-07-05
      • 1970-01-01
      • 2021-07-14
      • 2016-11-01
      • 1970-01-01
      相关资源
      最近更新 更多