angular - 在 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.section
了undefined
。我错过了什么?
解决方案
构造函数中的代码在组件接收更改之前执行,您需要将逻辑转移到ngOnInit
.
推荐阅读
- regex - 在 vim 中将 'U' 附加到所有数字
- flutter - 如何在 Flutter 中与来自 http 请求的 html 响应进行交互
- julia - 有条件地在 Julia 的另一个函数中定义一个函数
- sql - 合并两列并对结果执行 where 操作
- django - 如何让非pk值成为在django rest框架中发出post请求的值
- svg - SVG 奇数(随机)颜色
- clojure - Clojure:如何判断代码是在 REPL 还是 JAR 中运行?
- sql - 如何按字母顺序对同一部门进行排序
- java - 在TSP问题中仍然找不到返回原点的方法
- javascript - 如何为 webRTC 提供 STUN 服务器