[英]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. 我正在尝试将JSON hada加载到Angular 2组件中,我想我已经找到了方法。
datoer.service.ts: 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: 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. 我的问题是该组件中的this.datoer。 It says it does not exist on type KalenderComponent.
它说它在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'. 但是然后它说“类型'Observable'不能分配给类型'any []'。属性'length'在类型'Observable'中丢失。
Any ideas how to solve this? 任何想法如何解决这个问题?
The http service, according to Angular2 Http class docs , returns an observable
not an array with results, that's because it's made asynchronously. 根据Angular2 Http类docs的说法,http服务返回的不是
observable
的结果数组,这是因为它是异步生成的。 Therefore you must subscribe
to the observable
so you can feed your array when it gets notified
(this happens when http request is complete). 因此,您必须
subscribe
observable
以便在收到notified
时可以将其送入数组(这是在HTTP请求完成时发生的)。
For example: 例如:
public datoer: any[] = [];
constructor(
private valgteSkolerService: ValgteSkolerService,
private DatoService: DatoService) {
this.DatoService
.getDato()
.subscribe(datoer => { this.datoer = datoer; });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.