After much effort, I have finally figured out how to load JSON data into an Angular 2 Component.
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>= [];
constructor(private valgteSkolerService: ValgteSkolerService, private DatoService: DatoService) {
this.datoer = this.DatoService.getDato();
}
ngOnInit() {
this.valgteSkolerService.hentLagretData();
this.valgteSkoleRuter = this.valgteSkolerService.delteValgteSkoleRuter;
}
My template looks like this:
<p *ngFor="let dato of datoer"> {{dato}} </p>
The issue arises with "this.datoer" in the component. It shows an error stating that it does not exist on type KalenderComponent. I attempted to declare it in the component as follows:
private datoer: Array<any> = [];
However, another error popped up saying, "Type 'Observable' is not assignable to type 'any[]'. Property 'length' is missing in type 'Observable'."
Do you have any suggestions on how to resolve this?