MariusJ MariusJ - 9 months ago 85
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.


import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

export class DatoService {

dato: Array<any>;

constructor(private http: Http) {}

getDato() {
return this.http.request('./datoer.json')
.map(res => res.json());


import { Component } from '@angular/core';
import { ValgteSkolerService } from '../valgteSkoler.service';
import { DatoService } from './datoer.service';

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.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 Source

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[] = [];    
    private valgteSkolerService: ValgteSkolerService,
    private DatoService: DatoService) {

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