【问题标题】:Angular 4- *ngFor not functioning on Array of ObjectsAngular 4- *ngFor 在对象数组上不起作用
【发布时间】:2018-07-31 01:15:05
【问题描述】:

我在 html 端使用 *ngFor 对从 REST 服务接收的数据进行循环时遇到了一些问题,这就是我正在做的事情:

  getQuestionaire(type: String) {
    const url = `${this.questionaireTypeUrl}/${type}`;
    return this.http.get(url).map(
      (response: Response) => {const questioniares: any[] = response.json();
        return questioniares;
      }
    );
  }

这里我在其中一个 app.component.ts 中调用函数:

  ngOnInit() {
    this.route.params
    .subscribe(
      (params: Params) => {
        this.quesType = params['type'];
        this.questionaireService.getQuestionaire(this.quesType).subscribe(
          (questionaires: any[]) => {
            this.questionaire = questionaires;
            console.log(this.questionaire);
          }
        );
      }
    );
  }

这里我在 html 端使用 *ngFor 循环并动态创建表

<table class="table ">
      <thead>
        <tr>
          <th class="active">QUESTIONAIRE NAME</th>
          <th class="active">LEVEL</th>
          <th class="active">LAST MODIFIED</th>
          <th class="active">PUBLISHED BY</th>
          <th class="active">VALIDITY DATE</th>
        </tr>
      </thead>
      <tbody *ngFor="let questionaireEl of questionaire">
        <tr>
          <td>{{ questioniareEl.nameQuestionaire }}</td>
          <td>{{ questionaireEl.levelQuestionaire }}</td>
          <td>{{ questionaireEl.lastUser }}</td>
          <td>{{ questionaireEl.publishingUser }}</td>
         </tr>
      </tbody>
 </table>

问题:控制台记录了我循环的数据,它由一组对象组成,我不知道如何访问我需要显示的元素,请帮助!!

【问题讨论】:

  • 你能显示来自服务器的 json 响应吗?
  • 你需要| async吗?
  • 你可以试试{{ questioniareEl?.nameQuestionaire }} 吗?
  • 在类定义中是否用空数组声明了 questioniares?如果不设置为 []。
  • @match 这两种解决方案我都尝试过并且它们都有效......但我想知道通配符运算符的作用?

标签: angular


【解决方案1】:

你需要使用异步管道&lt;tr *ngFor="let questionaireEl of questionaire | async"&gt;...

或者你可以写

<td>{{ questioniareEl?.nameQuestionaire }}</td>
<td>{{ questionaireEl?.levelQuestionaire }}</td>
...

为了避免这个错误

【讨论】:

  • 是的,它为我解决了,谢谢!但是我想知道通配符运算符的作用?
  • 如果对象在 '?' 之前,此运算符会阻止评估表达式具有空值/未定义值。避免异常并且不会破坏您的应用程序
【解决方案2】:

?.来救援

通常当异步调用发生时,您完全不知道结果何时会到达/到达模板。但另一方面,模板会被解析为 HTML,它会希望显示来自异步调用的尚未到达的数据。
因此,在数据返回之前,?. 运算符将等待(& 不会抛出任何模板错误)。
一旦数据到达,?. 操作员允许打印到达的数据。

例如。

{{questioniareEl?.nameQuestionaire}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 2018-08-26
    • 2018-07-02
    • 2021-03-28
    • 2019-04-22
    相关资源
    最近更新 更多