...component.ts:
import { Component } from '@angular/core';
import { ValgteSkolerService } from '../valgteSkoler.service';
import { DatoService } from './datoer.service';
@Component({
selector: 'kalender',
providers: [DatoService],
templateUrl: 'app/kalendervisning/html/kalender.html'
})
export class KalenderComponent {
private selectedSchoolRoutes: Array<any> = [];
public dates: any[] = [];
constructor(private selectedSchoolService: ValgteSkolerService, private dateService: DatoService) {
this.dateService
.getDate()
.subscribe(dates => { this.dates = dates; });
}
ngOnInit() {
this.selectedSchoolService.fetchStoredData();
this.selectedSchoolRoutes = this.selectedSchoolService.sharedSelectedSchoolRoutes;
}
routeCount: number = 0;
j: number = 0;
weekOne(month: number, year: number) :Cell[] {
var cells: Array<Cell> = [];
this.routeCount = 0;
for (this.j = 1; this.j <= this.totalDays(month, year); this.j++) {
var cell = new Cell;
console.log(this.dates[this.j].date);
cell.id = this.dates[this.j].date;
cell.text = this.j;
cells.push(cell);
this.routeCount++;
this.j = this.j;
if (this.routeCount % 7 == 0 && this.routeCount != 0) {
break;
}
}
return cells;
}
class Cell {
id: string;
text: number;
}
...service.ts:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class DatoService {
date: Array<any>;
constructor(private http: Http) {}
getDate() {
return this.http.request('app/kalendervisning/datoer.json')
.map(res => res.json());
}
}
...json:
{
"date": "2016-08-01"
},
etc.
I am facing challenges with the
cell.id = this.dates[this.j].date
statement in the component.
Upon inspecting the browser, it appears that the dates
array is undefined until the entire code has been executed multiple times. Eventually, the array populates. When I examined this using console.log, it shows 9 undefined objects followed by the actual data, repeated twice inexplicably.
I suspect there might be an issue with the asynchronous loading of data, but I'm uncertain.
Could you offer any insights into why this behavior occurs and suggest a solution?