gpt4 book ai didi

javascript - 无法通过 Angular 2 数据绑定(bind)从服务访问返回的对象属性

转载 作者:行者123 更新时间:2023-11-30 08:30:13 24 4
gpt4 key购买 nike

过程

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

问题

我无法使用 {{obj.prop}} 访问对象属性,它会抛出错误 “无法读取未定义的属性 'prop'”。
但是,如果我尝试在组件中访问它,它会起作用。

代码

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

{
"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}}

关于javascript - 无法通过 Angular 2 数据绑定(bind)从服务访问返回的对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39041310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com