[英]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.