2017-06-26 86 views
0

我试着从帖子列表中获得第一个资产。该列表来自web api。ng对于奇怪的不同行为

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个格,只是用IDS 2。这是我期待的。

<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次。它记录图像存在的帖子,并重复不存在的值。

回答

1

在开发模式下,Angular运行会更改检测两次,以确保模型在第一次过后稳定。如果没有,你会看到一个错误(类似于“检查后表达式已经改变......”)。所以你会看到Angular为每个有图像的元素调用你的函数两次的结果。

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

查看this post了解更多详情。