使用收到的数据更新模板

时间:2016-10-17 10:28:47

标签: javascript angular typescript angular2-template

我已设法从发布请求中检索一组数据,但现在分配时,视图不会更新。

@Component({
  selector: 'news-section',
  templateUrl: './news-section.component.html',
  styleUrls: ['./news-section.component.scss'],
  providers: [ NewsService ],
})
export class NewsSectionComponent implements AfterViewInit {
  slider: any;
  stub: number[];
  articles: NewsItemComponent[];

  constructor(translate: TranslateService, private http: Http, public newsService: NewsService) {
    translate.setDefaultLang('en');
    translate.use('en');

    this.articles = [];

    newsService.getNews().subscribe( news => {
        let articles: Array<any> = [];
        news.map((res) => {
            articles.push(new NewsItemComponent(res.text, res.created_at
, 'author', res.id_str);
          });
          console.log('articles', articles);
          this.articles = articles;
      });
  }


}

我在console.log中看到文章列表已正确更新,但未反映视图中的更改。

<section id="news" sectionVisible>
  <div>
    <h1>{{ 'Nav.News' | translate }}</h1>
  </div>
  <div class="news-wrapper clear-fix">
      <div class="column carousel-cell" ngFor="#article of articles">
        <article>
        <a href="#" class="hovered">
          <div class="bg-hover">
            <p>
              Visit
            </p>
          </div>
        </a>
        <h2>News title</h2>
        <time>21.10.2015 16:30</time>
        <p>
          Etiam faucibus sodales leo, rutrum molestie nisi luctus in. Duis quis viverra diam, vitae hendrerit augue. Donec ultricies nisi vel placerat sodales. Donec varius convallis mauris egestas vulputate. Integer fermentum tincidunt hendrerit. Donec eget nisl
          eros. Pellentesque a fringilla lorem.
        </p>
        </article>
      </div>
  </div>
</section>

我需要添加一些监听器吗? 我查看了http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html,但我的角度知识仍然非常基础,需要一些解释

1 个答案:

答案 0 :(得分:2)

ngFor="#article of articles"

应该是

*ngFor="let article of articles"