[英]Angular 2 ngOnInit Called Twice With Error
我在Angular 2中遇到了一个奇怪的错误。我有两个类似的模板和类似服务的类似组件。 以下是它们如何工作的基础知识:
零件:
theData: any;
constructor(private _theService: TheService) {}
ngOnInit() {
this._theService.getData()
.subscribe(data => {
this.theData = data;
});
}
服务:
private _url = "http://url.net/api/Data";
constructor(private _http: Http) {
}
getData() {
return this._http.get(this._url)
.map(res => res.json());
}
这将返回一个对象数组,如:
[
{name: "Name 1"},
{name: "Name 2"}
]
并且模板显示如下:
<div *ngFor="let item of theData">{{ item.name }}</div>
然后,您可以单击进入一个项目的项目,该项目遵循与上述相同的策略,但service / api仅返回单个对象,并且模板不使用* ngFor,因为只显示一个项目。
所以它看起来像:
theItem = {name: "Name 1"} // what the service returns
<div>{{ theItem.name }}</div>
显示所有项目时一切都很好,但当我点击单个项目时,OnInit被调用两次,我在platform-browser.umd.js中出错,这在模板中确实是一个错误,因为它说它不能读取undefined
的属性name
(即theItem)。
我通过将单个项目的模板更改为:
<div>{{ theItem?.name }}</div>
起初我以为问题是模板在数据从服务加载之前呈现,所以添加?
固定它。 但是,在ngOnInit完成后,模板是否应该加载? 我的问题是,为什么要添加?
修复此问题,即使我在加载所有项目时在第一个模板中不需要它?
谢谢。
因为get
是异步的,所以它确实在加载数据之前开始渲染模板。 它将启动服务调用并且不会等待,它将继续处理。 添加?
允许它undefined
,然后在加载数据后适当渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.