Angular2 Read Json File Using Http
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: Respon
Solution 1:
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 herethis.myM = res;
this.someRandomFunction(res);
);
}
someRandomFunction(res){
console.dir(res);
}
<li><ahref="{{myM?.home_header?.whatis?.link_url}}"class="ripple-effect">{{myM?.home_header?.whatis?.link_name}}</a></li>
Solution 2:
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);
}
Post a Comment for "Angular2 Read Json File Using Http"