[英]Angular2 OnInit, not getting data from server
I'm having problems getting data from server using NgOnInit function. 我在使用NgOnInit函数从服务器获取数据时遇到问题。 With this data, I want to paint a plot using morris.js but i'm not getting that data.
有了这些数据,我想使用morris.js绘制一个图,但是我没有得到该数据。
I have a service that obtains all car reparations from DB and then I want to paint a daily plot of total reparations. 我有一项可从DB获得所有汽车赔偿的服务,然后想绘制每日总赔偿图。 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: 我已经导入并声明了OnInit:
import {Component, OnInit} from 'angular2/core';
export class DashBoard implements OnInit
I'm using angular beta 17. Thanks. 我正在使用角度beta17。谢谢。
This code is async 这段代码是异步的
this._reparacionsService.getReparacions().subscribe(rep => this.reparacions = rep.json());
this means that this.getLastWeek();
这意味着
this.getLastWeek();
in 在
ngOnInit() {
this.getReparacions();
this.getLastWeek();
is executed before this.reparacions = rep.json()
is executed 在
this.reparacions = rep.json()
执行之前执行
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. 这仅在其他调用(
getLastWeek()
,getReparacionsDia()`)不是异步的情况下才有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.