Reputation: 3702
trying to read json file from my local project for some basic config.
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:
<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 !!!
can anyone tell me where am I wrong ?
UPDATE
json file content:
{
"home_header":
{
"servicesweoffer":
{
"lable_name":"SERVICES WE OFFER",
"link_url":""
},
"pricing":
{
"lable_name":"PRICING",
"link_url":""
},
"contacutus":
{
"lable_name":"CONTACT US",
"link_url":""
}
}
}
Upvotes: 0
Views: 534
Reputation: 40677
console.dir(this.myM)
will print undefined
because
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
.
That is why if you place console.dir(res)
inside the callback it prints the value. So when you are assigning 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>
Upvotes: 1
Reputation: 2068
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);
}
Upvotes: 0