MariusJ MariusJ - 1 month ago 15
TypeScript Question

Load JSON data into Angular 2 Component

I am trying to load JSON hada into an Angular 2 Component, and I think I have found the way.

datoer.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('./datoer.json')
.map(res => res.json());
}
}


kalender.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>= [];
//private datoer: Array<any> = [];

constructor(private valgteSkolerService: ValgteSkolerService, private DatoService: DatoService) {
this.datoer = this.DatoService.getDato();
}

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


My template is like:

<p *ngFor="let dato of datoer"> {{dato}} </p>


My problem is the this.datoer above in the component. It says it does not exist on type KalenderComponent.
I have tried declaring it like this in the component:

private datoer: Array<any> = [];


But then it says that "Type 'Observable' is not assignable to type 'any[]'. Property 'length' is missing in type 'Observable'.

Any ideas how to solve this?

Answer

The http service, according to Angular2 Http class docs, returns an observable not an array with results, that's because it's made asynchronously. Therefore you must subscribe to the observable so you can feed your array when it gets notified (this happens when http request is complete).

For example:

public datoer: any[] = [];    
constructor(
    private valgteSkolerService: ValgteSkolerService,
    private DatoService: DatoService) {

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