简体   繁体   English

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

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

Process流程

I am using a service to get data (objects) from a json file with an observable and display them in the HTML template.我正在使用一项服务从带有 observable 的 json 文件中获取数据(对象),并将它们显示在 HTML 模板中。

Problem问题

I can't access the objects properties by using {{obj.prop}} , it throws an error "Cannot read property 'prop' of undefined".我无法使用{{obj.prop}}访问对象属性,它会引发错误"Cannot read property 'prop' of undefined".
However if I try to access it in the component, it works.但是,如果我尝试在组件中访问它,它会起作用。

Code代码

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

Template模板

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

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

您应该将{{data.header.title}}更改为{{data?.header?.title}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM