Show data from JSON Using Angular 2 - Observable and Asynchronous
I have a simple Angular 2 service calling a local JSON file. I can get the console.log object in a .map function in general.service.ts. However, due to the nature of the asynchronous call, I cannot print a single key or value from an object. here is my code.
I understand that I need to include * ngIf because it is asynchronous. However, although I used ngIf with "generalInfo" which refers to the .ts component
general.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { General } from '../interfaces/general.interface'
@Injectable()
export class GeneralService {
private dataAPI = '../../assets/api.json';
constructor(private http: Http) {
}
getGeneralData() : Observable<General> {
return this.http.get(this.dataAPI)
.map((res:Response) => { res.json(); console.log(res.json())})
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
}
header.component.ts
import { Component, OnInit, DoCheck } from '@angular/core';
import 'rxjs/add/operator/map';
import { GeneralService } from '../../services/general.service';
@Component({
selector: 'header',
templateUrl: `./header.component.html`
})
export class headerComponent implements OnInit{
public generalInfo : any;
public name : string;
constructor(
private headerblock: GeneralService
) {}
//Local Properties
header;
loadHeader() {
this.headerblock.getGeneralData()
.subscribe(
generalInfo => {
this.generalInfo = generalInfo;
this.name = this.generalInfo.name
},
err => {
console.log(err);
}
);
}
ngOnInit() {
this.loadHeader();
}
}
header.component.html
<div class="container">
<div *ngIf="generalInfo">
{{name}}
</div>
</div>
With this code, though at the moment - it doesn't go into the if statement. I'm not sure why this isn't working?
source to share
*ngIf
fails, the reason for your map
-function returns nothing.
So, in your subscribe
-function, the input value undefined
!
You should return something in your function map:
.map((res:Response) => { console.log(res.json()); return res.json(); })
And in your template, use it like this:
{{ generalInfo.name }}
Assuming it generalInfo
has a property named name
.
source to share