无法通过角度2数据绑定从服务访问返回的对象属性

时间:2016-08-19 14:17:36

标签: javascript json angular

过程

我正在使用一个服务从带有observable的json文件中获取数据(对象),并将它们显示在HTML模板中。

问题

我无法使用{{obj.prop}}访问对象属性,因此会引发错误"Cannot read property 'prop' of undefined". 但是,如果我尝试在组件中访问它,它就可以工作。

代码

  

contentService的

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

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

  getContent() {
   return this._http
     .get('./app/services/dataContent.json')
     .map((response:Response) => response.json())
     .do(response => console.log('response = ', response))
  }
}
  

TopContentComponent

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';
@Component({
  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() {
    this._ComponentContentService.getContent()
      .subscribe(
        (data) => {
          this.data = data;
        }
      );
  }
}
  

模板

<p>{{data.header.title}}<p>
  

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!"
  },
}

1 个答案:

答案 0 :(得分:5)

您应该更改{{data.header.title}}

{{data?.header?.title}}