我是Angular 2的新手,在此刻感到非常困惑。为什么我无法访问我的angular2类属性
我正在加载一个从服务中检索数据的组件(采用JSON格式),而且我显然没有成功设置属于我的类,我想要表示该数据。
但是我可以(带调试器)看到返回的数据和alert()
吧。我认为我正在设置属性,但模板报告一个错误,表示它不理解该属性。
所以,我有这样的:
import { Response } from '@angular/http';
import { Location } from '@angular/common';
import { ActivatedRoute, Params } from '@angular/router';
import { Component, Input, OnInit } from '@angular/core';
import 'rxjs/add/operator/switchMap';
import { SiteService } from './site.service';
import { Site } from './site';
@Component({
moduleId: module.id,
selector: 'site-detail',
templateUrl: 'site-detail.component.html'
})
export class SiteDetailComponent implements OnInit {
public site: Site; // **Site is an interface**
constructor(
private siteService: SiteService,
private route: ActivatedRoute,
private location: Location
) { }
// getSite(): void {
ngOnInit(): void {
this.route.params
.switchMap((params: Params) => this.siteService.getSite(params['id']))
.subscribe((data: Response) => {
this.site = data[0];
alert(this.site.sitex_invoiceAccount); ** ALL LOOKS GOOD AT THIS POINT **
})
}
}
的alert()
高兴地报告正确的invoiceAccount
值,这对我来说,我已经将数据分配给我的财产site
。
但是,模板是不相信这个片断:
<div class="form-group">
<label for="xxxx">Site ID</label>
<input type="text" class="form-control" [value]="site.sitex_invoiceAccount">
</div>
告诉我:
EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/site-detail.component.html:5:52 caused by: Cannot read property 'sitex_invoiceAccount' of undefined TypeError: Cannot read property 'sitex_invoiceAccount' of undefined
谁能告诉我,我犯敬请错误?
谢谢你仁慈的人。
哦,我的天啊,做一个基本的错误!谢谢,我想我假设模板会在** ngOnInit后显示** - 我显然需要阅读生命周期。 谢谢,我现在会尝试这些更改。 –
结果!非常感谢Stefan。 –