Jridi Hamza Jridi Hamza - 2 months ago 6
Javascript Question

can't access a returned object properties from a service by angular 2 data binding

In an Angular 2 app, I am using a service to get data(objects) from a json file by observable and use it in a component to display it in the HTML template.
the problem is that I cant access the objects properties by using {{obj.prop}} it throws an error "Cannot read property 'prop' of undefined".
but if I try to access it in the component it works.
I've been struggling with it all the day...any help please???
this is my code.

  • The Service


import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';

export class ComponentContentService {
constructor(private _http: Http) { }

getContent() {
return this._http
.map((response:Response) => response.json())
.do(response => console.log('response = ', response))

  • The Component

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

import { WowComponent } from '../libraries.components/wow.component/wow.component';
import { BackstretchComponent } from '../libraries.components/backstretch.component/jquery.backstretch.component';
import { ComponentContentService } from '../services/component.content.service';

selector: 'top-content',
templateUrl: './app/top-content.component/top-content.component.html',
directives: [WowComponent, BackstretchComponent]
export class TopContentComponent {
header : any;
description : any;
data : any;
constructor(private _ComponentContentService: ComponentContentService) {}

ngOnInit() {this.getComponentContent();}

getComponentContent() {
(data) => {
this.data = data;

  • The Template


  • JSON


    "header" : {
    "title":"Our New Course is Ready",
    "description" : "We have been working very hard"

    "Footer" : {

    "title":"Our New Course is Ready",
    "description" : "We have been working very hard to create the new version of our course. It comes with a lot of new features, easy to follow videos and images. Check it out now!"


You should change {{data.header.title}} for {{data?.header?.title}}