可以't通过angular 2数据绑定从服务访问返回的对象属性
can't access a returned object properties from a service by angular 2 data binding
流程
我正在使用一个服务从带有可观察对象的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))
}
}
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!"
},
}
您应该将{{data.header.title}}
更改为{{data?.header?.title}}
相关文章:
- AngularJS-需要在index.html页面中访问来自服务的数据
- Angular使服务可以从任何地方访问
- 从AngularJS中的另一个文件中的控制器访问服务
- 可以't访问Angular.js服务中的功能
- 无法使用javascript客户端访问远程web服务
- 使用typescript访问导入的服务时发生Angular2错误
- 服务变量分配了数据,但在访问时始终未定义
- 控制器切换后匿名功能中的访问服务数据发生变化
- 为什么我无法访问使用 $provide.provider 和 $injector.get 创建的服务
- 在 Jasmine 测试中无法访问 Angular 服务函数
- 从Web服务访问JSON响应
- 如何访问ng-init或ng-checked中服务回调函数中声明的$scope变量
- Microsoft认知服务JavaScript请求'访问控制允许来源'
- 如何正确访问es6中的AngularJS服务
- 如何访问回调函数之外的异步angularjs服务数据
- 从函数内部、类内部、模块内部访问 Angular 服务
- 从 Angular 控制器访问不同模块中的角度服务
- 如何通过绑定的控制器变量访问服务的属性
- 使用Angular服务和JavaScript类(在类中访问服务,或者在Angular框架中修改类)
- 如果angular视图直接访问服务,这是一个好习惯吗?