[英]angular2 read json file using http
trying to read json file from my local project for some basic config. 尝试从本地项目中读取json文件进行一些基本配置。
code: 码:
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: HTML:
<li><a href="{{myM.home_header.whatis.link_url}}" class="ripple-effect">{{myM.home_header.whatis.link_name}}</a></li>
but it always logs on console as undefined.. 但它始终以未定义的身份登录控制台。
if I place console.dir(res)
instead of value assign then it prints my object data but don't know why it does not assign to variable !!! 如果我放置
console.dir(res)
而不是赋值,那么它会打印我的对象数据,但不知道为什么它没有赋给变量!
can anyone tell me where am I wrong ? 谁能告诉我我哪里错了?
UPDATE 更新
json file content: json文件内容:
{
"home_header":
{
"servicesweoffer":
{
"lable_name":"SERVICES WE OFFER",
"link_url":""
},
"pricing":
{
"lable_name":"PRICING",
"link_url":""
},
"contacutus":
{
"lable_name":"CONTACT US",
"link_url":""
}
}
}
console.dir(this.myM)
will print undefined
because console.dir(this.myM)
将打印undefined
因为
this.http.get('config.json')
.map((res: Response) => res.json())
.subscribe(res => this.myM = res);
is an async operation. 是异步操作。 Meaning
http.get
will return you something after a time (depending on network speed and other stuff) and you can do something with this response inside the http callback which is inside subscribe
. 意味着
http.get
会在一段时间后返回您一些内容(取决于网络速度和其他因素),并且您可以在subscribe
的http回调内部使用此响应进行操作。
That is why if you place console.dir(res)
inside the callback it prints the value. 这就是为什么如果将
console.dir(res)
放在回调中会显示该值的原因。 So when you are assigning this.myM = res;
因此,当您分配
this.myM = res;
you are not doing anything wrong, it just takes a little time to do this operation. 您没有做错任何事情,只需花费一点时间即可执行此操作。
Example: 例:
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>
Scope of this not working in subscribe 此范围不适用于订阅
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.