我从服务器获取json
getTextContent() {
this._main.getVar()
.subscribe(
text_content => this.text_content = text_content,
error => console.error('Error: ' + this.errorMessage),
() => console.log('Completed!',this.text_content));
}
在控制台和屏幕上我看到了
那很好。但是当我尝试在屏幕上显示{{text_content.category_content.home}}
时,我收到错误TypeError: Cannot read property 'category_content' of undefined in [{{text_content.category_content.home}} in HomeComponent@1:3]
我应该使用dot来获取对象的属性还是其他任何东西?
更新
import {Component,OnInit} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';
import {MainService} from '../../shared/services/main.service';
import {Http} from 'angular2/http';
import {Title} from 'angular2/platform/browser';
@Component({
selector: 'sd-home',
moduleId: module.id,
viewProviders: [MainService],
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
directives: [CORE_DIRECTIVES]
})
export class HomeComponent implements OnInit {
public http:Http;
public pageTitle : String;
private text_content : Object;
private errorMessage : String;
constructor (private _title:Title, private _main:MainService) {
}
ngOnInit() {
this.getTextContent();
console.log('text',this.text_content.category_content);
}
getTextContent() {
this._main.getVar()
.subscribe(
text_content => this.text_content = text_content,
error => console.error('Error: ' + this.errorMessage),
() => console.log('Completed!',this.text_content));
}
}
属性'category_content'在'Object'
类型上不存在答案 0 :(得分:0)
您需要将text_content
放入$scope
。因此,在您的成功案例结束时,您需要$scope.text_content = this.text_content
。这将使消化器可以使用它并且它将被正确渲染。
答案 1 :(得分:0)
可能是angular2 zone
问题,
import {NgZone} from 'angular2/core';
constructor (private _title:Title, private _main:MainService,private zone:NgZone) {
}
getTextContent() {
this.zone.run(()=>
this._main.getVar()
.subscribe(
text_content => this.text_content = text_content,
error => console.error('Error: ' + this.errorMessage),
() => console.log('Completed!',this.text_content));
);
}
试试这个。
答案 2 :(得分:0)
使用
{{text_content?.category_content?.home}}
当Angular第一次尝试解析绑定时, text_content
尚未可用,因为数据处理为异步。