*ngfor 在 Angular7 中不显示任何数据

*ngfor not display any data in Angular7

我正在使用 angular7,这是我的代码: 在 component.ts

import { Component, OnInit } from "@angular/core";
import { FocusAreasService } from "../../services/focus-areas.service";

@Component({
  selector: "app-about",
  templateUrl: "./about.component.html",
  styleUrls: ["./about.component.scss"]
})
export class AboutComponent implements OnInit {
  public canonical: string;
  public RsFocusArea: any[];
  constructor(public focusareaService: FocusAreasService) {}

  ngOnInit() {
    this.canonical = document.location.origin;

    this.focusareaService.getFocusAreaDataWithHttpClient2().subscribe({
      next(response) {
        console.log("HttpClient handle data");
        console.dir(response);

        this.RsFocusArea = response["focusArea"];
       //I print this.RsFocusArea here , it has values 
        console.log("this.RsFocusArea");
        console.dir(this.RsFocusArea);
      },
      error(err) {
        console.error("Error: " + err);
      },
      complete() {
        console.log("Completed");
      }
    });
  }
}

}

并在.html

 <ul class="col-xs-12 row">
        <li *ngFor="let area of RsFocusArea" class="col-xs-12 col-sm-6 col-md-4">{{area}}
        </li>
      </ul>

li tage 没有重复并在标签结构中给了我这个:

<ul _ngcontent-aly-c5="" class="col-xs-12 row"><!--bindings={}--></ul>
<!--bindings={}-->
<ul _ngcontent-aly-c5="" class="col-xs-12 row"><!--bindings={}--></ul>

我的代码有什么问题吗?当我在 ngOnInit 中为 RsFocusArea 分配新值时,我想也许我需要重新呈现页面?

RsFocusArea = [1, 2, 3];

在模板中:

<li *ngFor="let area of RsFocusArea" class="col-xs-12 col-sm-6 col-md-4">
     {{area}}
</li>

https://angular-bchmnn.stackblitz.io

希望,它能解决您的问题。

订阅有问题

问题是你从来没有设置你真正想要的变量,你的组件的 this.RsFocusArea 永远不会得到一个值,你在订阅中调用的 this.RsFocusArea 变量在next(response){} 函数。


在您的 subscribe() 中使用 next(response){...} 将导致 this 关键字引用 next(response){} 函数,这意味着 this.RsFocusArea 不引用您组件的不再是变量,但它正在寻找一个未定义的变量。

(此处解释:

简而言之:this 关键字在其他函数中可能很棘手

要修复它:

尝试用箭头函数编写 subscribe

this.focusareaService.getFocusAreaDataWithHttpClient2().subscribe(
  response => {
    console.log("HttpClient handle data");
    console.dir(response);

    this.RsFocusArea = response["focusArea"];
    //I print this.RsFocusArea here , it has values 
    console.log("this.RsFocusArea");
    console.dir(this.RsFocusArea);
  },
  err => {
    console.error("Error: " + err);
  },
  () => {
    console.log("Completed");
  }
});

如果你真的想使用 next() 符号,你可以看看如何绑定函数。

希望对您有所帮助

天哪!我正在写 Jojofoulk 在这里发布的答案。至少我会用更少的语言向您解释为什么会发生这种情况。箭头函数保留声明它们的上下文,另一方面,函数声明保留局部作用域。

当你这样做时:

{
    ...
    this.RsFocusArea = response["focusArea"];
}

您正在函数局部范围内分配响应值,外部范围不会受到影响,因此当您打印值时您会看到响应,但您看到的是在局部范围内分配的本地结果.