我正在尝试显示REST API中的数据 . 但是,在加载数据之前呈现UI . 所以我收到以下错误:
无法读取未定义的属性“名称”
如何绑定对象?
组件:
@Component({
selector: 'foo-detail',
templateUrl: 'foo.component.html',
providers: [FooService],
})
export class FooDetailComponent implements OnInit {
public foo:Foo;
constructor(private fooService:FooService,
private route:ActivatedRoute) {
}
ngOnInit() {
this.route.params
.map(params => params['id'])
.subscribe(fooId => {
this.fooService
.get(+fooId)
.subscribe(res => this.foo = res);
});
}
}
服务:
@Injectable()
export class FooService {
constructor(private http: Http) {}
get(fooId) {
return this.http.get('http://api.foo.com/foos/' + fooId)
.map(res => res.json())
.map(foo => {
return new Foo(foo.id, foo.name, foo.description);
});
}
}
模板:
<ActionBar [title]="foo.name"></ActionBar>
<GridLayout>
<Label [text]="foo.description"></Label>
</GridLayout>
1 回答
您可以使用
ngIf
指令或安全导航操作符(?
)(也称为Elvis操作符)来"protect"您的模板:ngIf
指令猫王经营者
我建议阅读official Angular 2 page about ngIf directive以了解它是如何工作的,以及template syntax page about safe nagivation operator (?) .