尝试从我的本地项目中读取json文件以获得一些基本配置。
代码:
myM: any;
constructor(private http: Http) {
this.http.get('config.json')
.map((res: Response) => res.json())
.subscribe(res => {
this.parseHeaderJSON(res);
});
}
parseHeaderJSON(res) {
this.myM = res;
}HTML:
<li><a href="{{myM.home_header.whatis.link_url}}" class="ripple-effect">{{myM.home_header.whatis.link_name}}</a></li>但它总是以未定义的..的形式登录控制台
如果我放置console.dir(res)而不是值赋值,那么它会打印我的对象数据,但不知道为什么它不赋值给变量!
有人能告诉我我哪里错了吗?
更新
json文件内容:
{
"home_header":
{
"servicesweoffer":
{
"lable_name":"SERVICES WE OFFER",
"link_url":""
},
"pricing":
{
"lable_name":"PRICING",
"link_url":""
},
"contacutus":
{
"lable_name":"CONTACT US",
"link_url":""
}
}
}发布于 2016-12-12 06:14:00
console.dir(this.myM)将打印undefined,因为
this.http.get('config.json')
.map((res: Response) => res.json())
.subscribe(res => this.myM = res);是异步操作。这意味着http.get会在一段时间后返回一些内容(取决于网络速度和其他内容),您可以在subscribe内部的http回调中使用这个响应来完成一些事情。
这就是为什么如果在回调中放置console.dir(res),它会打印值。因此,当您分配this.myM = res;时,您没有做任何错误的事情,只需一点时间就可以完成此操作。
示例:
constructor(private http: Http) {
this.http.get('config.json')
.map((res: Response) => res.json())
.subscribe((res) => {
//do your operations with the response here
this.myM = res;
this.someRandomFunction(res);
);
}
someRandomFunction(res){
console.dir(res);
}<li><a href="{{myM?.home_header?.whatis?.link_url}}" class="ripple-effect">{{myM?.home_header?.whatis?.link_name}}</a></li>发布于 2016-12-12 06:13:31
此范围不适用于订阅。
myM: any;
constructor(private http: Http) {
let _self = this;
this.http.get('config.json')
.map((res: Response) => res.json())
.subscribe(
res => _self.myM = res
);
console.dir(this.myM);
}https://stackoverflow.com/questions/41095056
复制相似问题