0

I'm try get the first asset from a list of Posts. This list came from a 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);
      }
    }

the strange behavior happens on the front end side. blogPosts is a list of 4 but just 2 haven images.

if I try just print the values like this:

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

The result is 4 divs and just 2 with ids. It is what I'm expecting.

<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>

but in this case, console logs 4 times. It logs the post that images exist and repeats the value for that not exists.

LLai
  • 13,128
  • 3
  • 41
  • 45
AFetter
  • 3,355
  • 6
  • 38
  • 62

1 Answers1

1

In development mode, Angular runs change detection twice to ensure that the model has stabilized after the first pass. If not, you would see an error (something like "Expression has changed after it was checked..."). So you are seeing the result of Angular calling your function twice for each element that has an image.

If you run in production mode, your function will be called only once for each element that has an image.

Check out this post for more details.

Frank Modica
  • 10,238
  • 3
  • 23
  • 39