加载JSON数据在Angular 2中给出了未定义的对象 - 异步?

时间:2016-10-26 10:48:21

标签: json asynchronous angular typescript

... 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 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;
        for (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 } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from '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.

我正在努力处理组件中的cell.id = this.datoer[this.j].dato语句。 我检查了浏览器检查器,看起来datoer数组是未定义的,直到整个代码运行了好几次。过了一会儿,阵列就被填满了。当我用console.log测试它时,它打印9个未定义的对象,然后打印实际数据,但由于某种原因重复2次。 我认为可能存在数据未异步加载的问题,但我不确定。 有没有想法为什么它会像这样,你有解决方案吗?

1 个答案:

答案 0 :(得分:0)

ngOnInit中添加调用API的constrctor代码:

ngOnInit() {
  this.DatoService
    .getDato()
    .subscribe(datoer => { this.datoer = datoer; });

  this.valgteSkolerService.hentLagretData();
  this.valgteSkoleRuter =     this.valgteSkolerService.delteValgteSkoleRuter;
}