ngFor 奇怪的不同行为

ngFor weird different behavior

我正在尝试从帖子列表中获取第一个资产。此列表来自网络 api.

import { Component, OnInit } from '@angular/core';
import { BlogPostService } from '../services/blog-post.service';
import { BlogPost } from '../modules/blog-post';

@Component({
  selector: 'af-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})    
export class HomeComponent implements OnInit {

      blogPosts: BlogPost[];
      skip: number;
      showPrevious = false;
      constructor(private blogService: BlogPostService) { }

      ngOnInit() {
        this.skip = 0;
        this.getPosts(this.skip);
      }

      getPosts(skip: number) {
        this.skip = skip;

        this.blogService.getBlogPosts(skip).subscribe(dt => this.blogPosts = dt});
      }
      getAssetById(id: string) {
        console.log('id:', id);
      }
    }

奇怪的行为发生在前端。 blogPosts 是一个包含 4 个但只有 2 个避风港图片的列表。

如果我尝试像这样打印值:

<div class="col-sm-6" *ngFor="let post of blogPosts">
      <div class="card">
        {{ post.fields.images && post.fields.images[0].sys.id}}
      </div>
 </div>

结果是 4 个 div,只有 2 个带有 ID。这正是我所期待的。

<div class="col-sm-6" *ngFor="let post of blogPosts">
      <div class="card">
        {{ post.fields.images && getAssetById(post.fields.images[0].sys.id) }}
      </div>
</div>

但在本例中,控制台记录了 4 次。它记录图像存在的 post 并重复不存在的值。

在开发模式下,Angular 运行s变化检测两次,确保模型在第一遍后已经稳定。否则,您会看到一个错误(类似于 "Expression has changed after it was checked...")。因此,您将看到 Angular 为每个具有图像的元素调用您的函数两次的结果。

如果您 运行 在生产模式下,您的函数将只为每个有图像的元素调用一次。

查看 了解更多详情。