gpt4 book ai didi

javascript - angular2使用http读取json文件

转载 作者:行者123 更新时间:2023-12-03 05:27:25 25 4
gpt4 key购买 nike

尝试从我的本地项目读取 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":""
}
}
}

最佳答案

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>

关于javascript - angular2使用http读取json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41095056/

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