我有以下界面;
export interface IDetail {
name: string;
office: string;
addresses: Address[];
}
interface Address{
street: string;
zip: number;
}
我的服务方法,
getDetails(id: number): Observable<IDetail> {
return this._http.get(this._apiUrl+ "/" + id)
.map((response: Response) => <IDetail>response.json())
.catch(this.handleError);
在组件ngOnInit方法上,
ngOnInit(): void {
this.getDetailsService(id)
.subscribe(data => {
this.detail = data;
console.log(this.detail);
this.AccessAddress();
},
error => this.errorMessage = <any>error);
}
AccessAddress(): void{
//After service call, trying to read addresses member
let addresses = this.detail.addresses;
}
在subscribe方法中,我在控制台中看到IDetail的输出。
在服务调用之后,当尝试读取地址成员时,我得到以下错误, 错误类型错误:无法读取属性&#39;地址&#39;未定义的
在html文件中,我可以访问地址成员并在UI上显示。
<div *ngFor="let address of detail.addresses">
{{address.street}}
</div>
我是否需要更改界面才能上课?或者我需要在访问地址之前初始化地址成员?或Observable的其他东西?
答案 0 :(得分:0)
所以问题在于你打电话
let addresses = this.detail.addresses;
地址未定义,因为您的服务调用尚未返回,因此详细信息也未定义。我建议在服务调用中设置代码,并将其初始化为最初为空
ngOnInit(): void {
this.getDetailsService(id)
.subscribe(data => {
this.detail = data;
console.log(this.detail);
let addresses = this.detail.addresses;
},
error => this.errorMessage = <any>error);
detail={
addresses:[]
}
}
如果需要,在加载时使用空输入在服务调用之外初始化它。
答案 1 :(得分:0)
您还可以在成功订阅中调用函数,以便处理地址。
ngOnInit(): void {
this.getDetailsService(id)
.subscribe(data => {
this.detail = data;
console.log(this.detail);
this.processAddresses();
},
error => this.errorMessage = <any>error);
}
processAddresses(){
//Here you can process adderesses
let addresses = this.detail.addresses;
//...
}
答案 2 :(得分:0)
我解决了实施路线解析器的问题。我错过了角度基础: - (