简体   繁体   中英

Angular 2 Dashboard application web api call at initialization

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?

http://preview.themeforest.net/item/avenxo-responsive-angularjs-html-admin/full_screen_preview/11660185?ref=cirvitis&clickthrough_id=1107952073&redirect_back=true

To build your application in the way the Angular team intended would mean putting any API calls into an injectable service. Check out @Injectable . From there you would inject the service into any component or directive that needs to make the API calls.

Also, the API calls are likely async which may be part of the reason you are getting null. These must be handled in Observables or Promises/Callbacks.

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;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM