Ton*_*ild 11 binding asynchronous httprequest string-interpolation angular
我是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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
渲染模板时,我收到错误,因为尚未设置"模型".
我用这个非常丑陋的黑客解决了这个问题:
@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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何推迟模板渲染,直到我的http调用完成或如何直接在模板中插入"模型"值而不绑定到另一个组件?
谢谢!
Mar*_*cok 12
如果从服务器返回对象,则可以在模板中使用安全导航(以前称为"Elvis")运算符(?.):
@Component({
selector: 'info',
template: `<h1>{{model?.Name}}</h1>`
})
export class InfoComponent implements OnInit {
model: any;
constructor(private _service: BackendService) { }
ngOnInit() {
this._service.getData().subscribe(m => this.model = m);
// getData() looks like the following:
// return this._http.get('....') // gets JSON document
// .map(data => data.json());
}
}
Run Code Online (Sandbox Code Playgroud)
看到这个答案的工作的plunker.
| 归档时间: |
|
| 查看次数: |
7061 次 |
| 最近记录: |