Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Interpolation and binding with async http request

I'm new to Angular 2 and I'm facing a problem with async http request and binding with interpolation.

Here's my component:

@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();
        }     
    }
}

When the template is rendered I get an error because "model" is not set yet.

I solved the problem with this very ugly 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();
        }     
    }
}

My question is: how to defer the template rendering until my http call is completed or how interpolate the "model" values directly in template without binding to another component?

Thanks!

like image 566
Tony Alexander Hild Avatar asked Jan 26 '16 16:01

Tony Alexander Hild


1 Answers

If you are returning an object from your server, you can use the safe navigation (previously "Elvis") operator (?.) in your template:

@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()); 
    }
}

See this answer for a working plunker.

like image 92
Mark Rajcok Avatar answered Sep 23 '22 15:09

Mark Rajcok