Frenchi In LA Frenchi In LA - 5 months ago 66
JSON Question

Angular 2 http service

I'm learning Ang2. I ran the Hero tutorial successfully. to practice, I just added a link in the main page to a get a new component. there is a json file with a list of Radio Station. the following are my service, and the Component:

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;

}


and the Component is:

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()


}
}


the problem is the call of service is coming first, and no Radio is return while when the service is called with console.log I see that's is successful and get all records from JSON file. Any help would be greatly appreciated.

Answer

You can't get data this way from async calls (which is when you use Promise or Observable). Http returns and Observable. You need to subscribe() and in the callback you pass to subscribe(...) you get the data and can assign it to local properties.

And example how you can solve this:

In getRadios we don't call subscribe() and use map() instead. map() returns an Observable which allows the caller to get the data. subscribe() returns a Subscription and doesn't allow to get the response data, it only allows to cancel the subscription (which is also often handy, but not now ;-) ).

getRadios() {
    console.log('Radios Service is being called');
    return this.http.get('app/mock/FranceRadioJSON.json')
        .map((res: Response) => res.json())
        .map((rad: Radio[]) => {      // Succes
            console.log('Radios Service Success');
            this.radios = rad;
            this.len = rad.length;
        });
}

We subscribe in getRadios because here we want to get the data. When we subscribe, the map() calls in getRadios are executed as well. subscribe() makes the Observable actually do its work:

getRadios() {
    this.radios = this.radioservice.getRadios()
        .subscribe((radios) => {
           this.radios = radios;
        } , 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)
        });

    // executed before the HTTP get call to the server
    // console.log('radio component NB: ' + this.radios.length);
}

Because data is not returned immediately but only when the callback passed to subscribe(...) is executed you can get errors for bindings like

<div>{{radios.xxx}}</div>

when radios is still null when Angular2 already resolves the bindings in the template. To avoid errors you can use the safe-navigation (Elvis) operator

<div>{{radios?.xxx}}</div>

Angular2 doesn't try to access .xxx while radios is null.

Comments