所以我有一个组件和服务....服务进行API调用并填充组件的变量(this.data)
在组件方面,一切运作良好,战略位置上的console.log总是返回值......这很直接
当我想在视图中显示数据时(让我们说{{data.name}},我收到错误...无法读取未定义的属性'name'
这个错误实际上是在我放入我的服务电话的console.logs之前打印出来的....所以我认为它不等待电话回来......
import { Component, OnInit } from '@angular/core';
import { Router, ROUTER_DIRECTIVES } from '@angular/router';
import { Index, IndexColumn } from '../index';
import { IndexService } from '../index.service';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'ex'})
export class StringifyPipe implements PipeTransform {
transform(value: any): string {
return JSON.stringify(value);
}
}
@Component({
moduleId: module.id,
selector: 'app-index',
template: require('./indicesDetails.component.html'),
styleUrls: [String(require('./indicesDetails.component.less'))],
providers: [IndexService],
pipes: [StringifyPipe]
})
export class IndicesDetailsComponent implements OnInit {
errorMessage: string;
index: Index;
mode = 'Observable';
constructor (private indexService: IndexService, private router: Router) {}
ngOnInit() {
this.getDetails('AAAAAA');
}
getDetails(id:string) {
this.indexService.getIndex()
.subscribe(
data => {
console.log(data);
this.index = data;
},
error => this.errorMessage = <any>error
);
}
}
观点:
<main>
<h1>INDEX DETAILS</h1>
<h4>{{index | ex}}</h4>
<h5>{{index.name}}</h5>
<p>This is the home page</p>
</main>
如果我没有将index.name中的index.name打印出来,则index.name会抛出提到的错误
答案 0 :(得分:6)
由于index
是异步加载的,因此该属性在开头时为null。您需要利用Elvis运算符来防止出现错误:
<main>
<h1>INDEX DETAILS</h1>
<h4>{{index | ex}}</h4>
<h5>{{index?.name}}</h5> <------
<p>This is the home page</p>
</main>