我正在学习Ang2。我成功地运行了英雄教程。为了练习,我只是在主页面添加了一个链接来获得一个新组件。有一个带有电台列表的json文件。以下是我的服务和组件:Angular 2 http服务
import { Radio } from '../models/radio';
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/Rx';
@Injectable()
export /**
* RadioService
*/
class RadioService {
radios: Radio[] = [];
len: Number = 0;
http: Http;
constructor(http: Http) {
this.http = http;
}
getRadios() {
console.log('Radios Service is being called');
this.http.get('app/mock/FranceRadioJSON.json')
.map((res: Response) => res.json())
.subscribe((rad: Radio[]) => { // Succes
console.log('Radios Service Success');
this.radios = rad;
this.len = rad.length;
}
, err => {// Failure
console.log('Radio Services Failure');
console.error(err);
}
, // complete
() => {
console.log('Get Radios Complete');
console.log('Records NB: ' + this.len);
console.log('radios nb: ' + this.radios.length)
}
)
;
return this.radios;
}
和组件是:
import { Component, OnInit } from '@angular/core';
import { RouteParams } from '@angular/router-deprecated';
import { Radio } from '../../models/radio';
import { RadioService } from '../../services/radio.service';
@Component({
selector: 'radio'
, templateUrl: 'app/html/radio.component.html'
, providers: [RadioService]
})
export /**
* RadioComponent
*/
class RadioComponent {
radios: Radio[] = [];
constructor(
private radioservice: RadioService) {
}
getRadios() {
this.radios = this.radioservice.getRadios();
console.log('radio component NB: ' + this.radios.length);
}
ngOnInit() {
this.getRadios()
}
}
的问题是服务的呼叫首先来了,也没有收音机是而当服务回报用console.log调用我看到这是成功的,并从JSON文件获取所有记录。任何帮助将不胜感激。
感谢您的详细解释。我看到更好的过程。 –
如何强制服务返回Radio [],还是应该将组件中的响应转换? –
您没有提供'Radio'类(或接口),也没有提供数据看起来像从observable获得的样子。没有完整的信息很难说清楚。 http://stackoverflow.com/questions/22885995/how-do-i-initialize-a-typescript-object-with-a-json-object可能是你在找什么。 –