Angular 2 - 使用异步http请求进行插值和绑定

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.

  • @TonyAlexanderHild,在角度变化检测期间(在每个事件之后运行),默认情况下,所有视图/模板绑定都被脏检查,这意味着它们会被检查是否有变化.当数据从服务器返回时,这是一个事件,因此更改检测运行.`model.Name`被脏检查并发现已经改变,因此Angular更新了DOM.在Angular将控制权返回给浏览器之后,它会看到DOM更改并更新我们在屏幕上看到的内容. (2认同)