首页 > 解决方案 > 在 Angular 8 中使用 @Input 的问题

问题描述

我正在处理我的第一个 Angular 项目,我的家庭组件 html 如下所示

<div class="container">
  <div>
    <div class="col-md-4">
      <h1 id="tableLabel">Latest</h1>
      <news-item [section]="Latest"></news-item>
    </div>
    <div class="col-md-4">
      <h1 id="tableLabel">STEM Stuff</h1>
      <news-item [section]="STEM"></news-item>
    </div>
  </div>
</div>

新闻项目的 ts 如下

import { Component, Inject, Input } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Component({
    selector: 'news-item',
    templateUrl: './news-item.component.html',
})

export class NewsItemComponent {

    public newsitems: NewsItem[];

    @Input() section: string;

    constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {

            http.get<NewsItem[]>(baseUrl + 'newsitems/GetNewsItemsBySection/' + this.section).subscribe(result => {

                this.newsitems = result;

            }, error => console.error(error));
    }
}

我在构造函数中得到this.sectionundefined。我错过了什么?

标签: angular

解决方案


构造函数中的代码在组件接收更改之前执行,您需要将逻辑转移到ngOnInit.


推荐阅读