Loading JSON data gives undefined object in Angular 2 - asynchronous? -
...component.ts:
import { component } '@angular/core'; import { valgteskolerservice } '../valgteskoler.service'; import { datoservice } './datoer.service'; @component({ selector: 'kalender', providers: [datoservice], templateurl: 'app/kalendervisning/html/kalender.html' }) export class kalendercomponent { private valgteskoleruter: array<any> = []; public datoer: any[] = []; constructor(private valgteskolerservice: valgteskolerservice, private datoservice: datoservice) { this.datoservice .getdato() .subscribe(datoer => { this.datoer = datoer; }); } ngoninit() { this.valgteskolerservice.hentlagretdata(); this.valgteskoleruter = this.valgteskolerservice.deltevalgteskoleruter; } antallruter: number = 0; j: number = 0; ukeen(mnd: number, aar: number) :cell[] { var cells: array<cell> = []; this.antallruter = 0; (this.j = 1; this.j <= this.antalldager(mnd, aar); this.j++) { var cell = new cell; console.log(this.datoer[this.j].dato); cell.id = this.datoer[this.j].dato; cell.text = this.j; cells.push(cell); this.antallruter++; this.j = this.j; if (this.antallruter % 7 == 0 && this.antallruter != 0) { break; } } return cells; } class cell { id: string; text: number; }
...service.ts:
import { injectable } '@angular/core'; import { http, response } '@angular/http'; import { observable } 'rxjs/observable'; @injectable() export class datoservice { dato: array<any>; constructor(private http: http) {} getdato() { return this.http.request('app/kalendervisning/datoer.json') .map(res => res.json()); } }
...json:
{ "dato": "2016-08-01" }, etc.
i struggling cell.id = this.datoer[this.j].dato
statement in component. have checked browser inspector, , seems datoer
array undefined until whole code has been run through several times. after while, array gets filled up. when tested console.log, prints 9 undefined objects, , actual data, reason repeated 2 times also. think there might problem data not loaded asynchronously, i'm not sure. there ideas why acts this, , have solution?
add constrctor code of calling api inside ngoninit
:
ngoninit() { this.datoservice .getdato() .subscribe(datoer => { this.datoer = datoer; }); this.valgteskolerservice.hentlagretdata(); this.valgteskoleruter = this.valgteskolerservice.deltevalgteskoleruter; }
Comments
Post a Comment