繁体   English   中英

Angular2 OnInit,未从服务器获取数据

[英]Angular2 OnInit, not getting data from server

我在使用NgOnInit函数从服务器获取数据时遇到问题。 有了这些数据,我想使用morris.js绘制一个图,但是我没有得到该数据。

我有一项可从DB获得所有汽车赔偿的服务,然后想绘制每日总赔偿图。 我得到的赔偿是无效的,我什么也画不出来。

我的代码:

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

我已经导入并声明了OnInit:

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

我正在使用角度beta17。谢谢。

这段代码是异步的

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

这意味着this.getLastWeek();

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

this.reparacions = rep.json()执行之前执行

您可能想要做类似的事情

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

这仅在其他调用( getLastWeek() ,getReparacionsDia()`)不是异步的情况下才有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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