簡體   English   中英

無法通過 angular 2 數據綁定訪問從服務返回的對象屬性

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

流程

我正在使用一項服務從帶有 observable 的 json 文件中獲取數據(對象),並將它們顯示在 HTML 模板中。

問題

我無法使用{{obj.prop}}訪問對象屬性,它會引發錯誤"Cannot read property 'prop' of undefined".
但是,如果我嘗試在組件中訪問它,它會起作用。

代碼

內容服務

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

頂部內容組件

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

您應該將{{data.header.title}}更改為{{data?.header?.title}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM