I have a dashboard application written in angular 2. I am using API call for the the data. After retrieving the data I render them in the graph. As the demo link below. When I make a API call from ngOnInit()
method of dashboardcomponent
I get null response but if I do same thing using a button click event all data loads as expected.
What is the best place/initiate to make a API call and populate all the data in UI at the first load itself?
ngOnInit() was ok to make the api call. I didn't have clear picture of subscribe function . I had to do couple of complex calculation in my typescript file before rendering in the UI. I should be doing this in the subscribe method only. not to assign with a global variable and do a dot operator and expect things to work like charm. I found that until you have listener subscribe does not hold data for your. Meaning if you have large json with nested elements you have to do this.data.innerdata[0].finalvalue[0] in the subscribe method instead pass that to method and do all the fun stuffs.
Pass your information to initData(data) and do all calculation and do the rendering.
export class Recent implements OnInit{
allFiles;
public allFiles_error:Boolean = false;
openModalWindow:boolean=false;
images = [];
currentImageIndex:number;
opened:boolean=false;
imgSrc:string;
constructor(private _recentService: RecentService) { }
ngOnInit() {
this._recentService.getJson().subscribe(
data => initData(data),
err => handleError(),
() => console.log('Completed!'));
}
initData(data){
this.allFiles = data;
console.log("allFiles: ", this.allFiles);
console.log(this.allFiles.length);
for(var i = 0; i < this.allFiles.length; i++) {
this.images.push({
thumb: this.allFiles[i].url,
img: this.allFiles[i].url,
description: "Image " + (i+1)
});
}
console.log("Images: ", this.images);
console.log(this.images.length);
console.log(this.images);
console.log(typeof this.images);
}
handleError() {
this.allFiles_error = true;
}
}