Я учу Ang2. Я успешно закончил учебник Hero. для практики я просто добавил ссылку на главной странице, чтобы получить новый компонент. есть json-файл со списком Radio Station. следующее мое обслуживание, а также компонент:Угловая 2 http service
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 [], или мне нужно преобразовать ответ в Component? –
Вы не предоставили класс «Радио» (или интерфейс), а также не то, как данные выглядят так, как вы получаете от наблюдаемого. Трудно сказать без полной информации. http://stackoverflow.com/questions/22885995/how-do-initialize-a-typescript-object-with-a-json-object может быть тем, что вы ищете. –