代码之家  ›  专栏  ›  技术社区  ›  AFetter

奇怪的不同行为

  •  0
  • AFetter  · 技术社区  · 7 年前

    我正在尝试从帖子列表中获取第一个资源。此列表来自web 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>
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   Frank Modica    7 年前

    在开发模式下,Angular运行两次更改检测,以确保模型在第一次通过后稳定。如果没有,您将看到错误(例如“检查后表达式已更改…”)。因此,对于每个具有图像的元素,您将看到两次调用函数的结果。

    如果在生产模式下运行,则对于具有图像的每个元素,只会调用一次函数。

    退房 this post