【发布时间】:2016-05-03 07:34:39
【问题描述】:
我是 Angular 2 的新手,我遇到了异步 http 请求和插值绑定的问题。
这是我的组件:
@Component({
selector: 'info',
template: `<h1>{{model.Name}}</h1>`
})
export class InfoComponent implements OnInit {
model: any;
constructor(
private _service: BackendService
) { }
ngOnInit() {
if (this.model == null) {
this._service.observableModel$.subscribe(m => this.model = m);
this._service.get();
}
}
}
渲染模板时出现错误,因为“模型”尚未设置。
我用这个非常丑陋的 hack 解决了这个问题:
@Component({
selector: 'info',
template: `
<template ngFor #model="$implicit" [ngForOf]="models | async">
<h1>{{model.Name}}</h1>
</template>
`
})
export class NeadInfoComponent implements OnInit {
models: Observable<any>;
constructor(
private _service: BackendService
) { }
ngOnInit() {
if (this.models == null) {
this._service.observableModel$.subscribe(m => this.models = Observable.of([m]));
this._service.get();
}
}
}
我的问题是:如何推迟模板渲染直到我的 http 调用完成,或者如何直接在模板中插入“模型”值而不绑定到另一个组件?
谢谢!
【问题讨论】:
标签: asynchronous binding httprequest angular string-interpolation