Mujahid Mujahid - 22 days ago 8
TypeScript Question

Data not binding issue in angular 2

I'm new to angular 2 and in my component's

ngOnInit()
I'm calling a service to get some data. This is my component
ngOnInit()
code

import { Component, OnInit } from '@angular/core';

import { Model } from './model';
import { CustomizeModelService } from './customize-model.service';

@Component({
selector: 'app-customize-model',
templateUrl: './customize-model.component.html',
styleUrls: ['./customize-model.component.scss']
})
export class CustomizeModelComponent implements OnInit {

models = [];

constructor(private custModelService: CustomizeModelService) {}

ngOnInit() {
let params = JSON.stringify({
"query": "{models(modelname: \"TestModel\") {_id, modelname, description}}"
});
this.custModelService.getModelByName(params).subscribe(data => {
this.models.push(data);
console.log(this.models);
});
}

}


It returns the data, but in my templates when I interpolate the data, it doesn't show anything

<h3 class="title">{{models.modelname}}</h3>


I'm not sure where did I make the mistake, or why the data is not getting bound to the template, Any help will be highly appreciated. Any more code required, I can provide

TIA

Answer

In Angular 2 Each Http service method returns an Observable of HTTP Response objects so you have to subscribe for its response as below :

this.custModelService.getModelByName(params).subscribe(data => {
  this.models.push(data);
  console.log(this.models);
});