简体   繁体   中英

Angular2 OnInit, not getting data from server

I'm having problems getting data from server using NgOnInit function. With this data, I want to paint a plot using morris.js but i'm not getting that data.

I have a service that obtains all car reparations from DB and then I want to paint a daily plot of total reparations. I'm getting a void array of reparations and I can't paint anything.

My code:

constructor(_router: Router, public http: Http, private _reparacionsService: ReparacioService) {
    this.router = _router;
}

getReparacions() {
    this._reparacionsService.getReparacions().subscribe(rep => this.reparacions = rep.json());
}

ngOnInit() {
    this.getReparacions();
    this.getLastWeek();
    this.getReparacionsDia();
    window['Morris'].Line({
        element: 'repDaychart',
        data: this.reparacionsDies,
        xkey: 'data',
        ykeys: ['totalReparacions'],
        labels: ['totalReparacions'],
        parseTime: false,
        xLabels: "day"
    });
}

I already imported and declared OnInit:

 import {Component, OnInit} from 'angular2/core';
  export class DashBoard implements OnInit 

I'm using angular beta 17. Thanks.

This code is async

this._reparacionsService.getReparacions().subscribe(rep => this.reparacions = rep.json());

this means that this.getLastWeek(); in

ngOnInit() {
    this.getReparacions();
    this.getLastWeek();

is executed before this.reparacions = rep.json() is executed

You probably want to do something like

getReparacions() {
    return this._reparacionsService.getReparacions().map(rep => this.reparacions = rep.json());
}

ngOnInit() {
  this.getReparacions().subscribe(data => {
    this.getLastWeek();
    this.getReparacionsDia();
    window['Morris'].Line({
        element: 'repDaychart',
        data: this.reparacionsDies,
        xkey: 'data',
        ykeys: ['totalReparacions'],
        labels: ['totalReparacions'],
        parseTime: false,
        xLabels: "day"
    });
  });
}

This only works if not other calls ( getLastWeek() , getReparacionsDia()`) are async as well.

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