如何修复ERROR TypeError:“ _ co.news未定义”?

时间:2019-07-03 20:38:59

标签: javascript angular

我正在尝试从后端获取一些数据以将其显示在组件上。 一切正常,但不知何故我收到此错误:错误TypeError:“ _ co.news未定义”。 有人有类似问题吗?

export class HomeComponent implements OnInit {

  isMobileResolution: boolean;

  news: News[] = [];

  constructor(private newsService: NewsService) {
  }

  ngOnInit() {
    this.readNews();
  }

  readNews(){
    this.newsService.readNews().subscribe((news: News[])=>{
      this.news = news;
    })
  }

}

<container *ngIf="!isMobileResolution">
  <news-card 
    [title]="news[0].title"
    [date]="news[0].date"
    [preview]="news[0].preview">
  </news-card>
  <div id="news-area">
    <news-card
      id="left"
      [lessText]="true"
      [title]="news[1].title"
      [date]="news[1].date"
      [preview]="news[1].preview">
    </news-card>
    <news-card
      id="right"
      [lessText]="true"
      [title]="news[2].title"
      [date]="news[2].date"
      [preview]="news[2].preview">
    </news-card>
  </div>
</container>

1 个答案:

答案 0 :(得分:0)

您可以更改ngIf:

<container *ngIf="!isMobileResolution && news?.length >= 3">