【问题标题】:ngFor does not load the dynamically populated array on NavigationEnd event Angular 6+ngFor 不会在 NavigationEnd 事件 Angular 6+ 上加载动态填充的数组
【发布时间】:2018-11-17 07:10:52
【问题描述】:

在我的类的构造函数中,在 NavigationEnd 事件中使用 ngFor 显示数组时出现问题

testArray = [];

constructor(private activatedRoute: ActivatedRoute, private router: Router) {
    this.router.events.forEach(event => {
        if (event instanceof NavigationEnd) {
            this.testArray = [1, 2, 3,4];
        }
    });
}


<ol class="breadcrumb">
    <li *ngFor="let element of testArray"
        class="breadcrumb-item">
        {{element}}
    </li>
</ol>

即使在 NavigationEnd 事件发生时填充了数组,它也不会显示数组的内容。 html 页面似乎没有重新加载新的数组数据。 任何帮助将不胜感激。

谢谢

【问题讨论】:

  • 当我在 StackBlitz stackblitz.com/edit/…987654321@ 中尝试时,它似乎有效
  • 我正在使用角度 ~7.0.4。可以是版本吗?
  • 不太可能,StackBlitz 使用的是 7.0.1,所以几乎相同。如果在forEach 中添加console.log,它会被打印吗?
  • 它会打印 console.log 但没有 html。我的组件是一个嵌套元素。会有所作为吗?
  • 您能否将重现所需的最少代码复制到 StackBlitz 中?

标签: javascript angular typescript


【解决方案1】:

如果你在这里使用异步管道会更好

testArray: Observable<number[]>;

constructor(private activatedRoute: ActivatedRoute, private router: Router) {
    testArray = this.router.events.pipe(filter(event) => event instanceof NavigationEnd).map(() => [1, 2, 3,4])
}

<ol class="breadcrumb">
    <li *ngFor="let element of testArray | async" class="breadcrumb-item">
        {{element}}
    </li>
</ol>

【讨论】:

  • 还是一样
  • this.testArray = this.router.events .pipe(filter((event) => event instanceof NavigationEnd), map(() => [1, 2, 3,4]));
【解决方案2】:

在设置值时使用setTimeout

   testArray = [];
       constructor(private activatedRoute: ActivatedRoute,
              private router: Router) {
    this.router.events.forEach(event => {
      if (event instanceof NavigationEnd) {
        setTimeout(()=>{
           this.testArray = [1, 2, 3,4];
        });

      }
    });
  }

【讨论】:

    【解决方案3】:

    视图似乎在数组填充之前加载。你可以尝试让你的类在“@angular/core”中实现“OnInit”,并在“ngOnInit”方法上创建foreach:

    ngOnInit() {
        this.router.events.forEach(event => {
          if (event instanceof NavigationEnd) {
            this.testArray = [1, 2, 3,4];
          }
        });
      }
    

    【讨论】:

    • ngOnInit() { this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { //当导航结束时调用这个东西 this.testArray = [1, 2, 3, 4];}}); }
    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多