John Smith
John Smith

Reputation: 483

How to extract data from angular http.get.subscribe

I'm using the Ionic 2 Calendar to display class times that have been subscribed to as json from a remote server. I am trying to extract the response from my subscription and put it into an array, but when putting the data out to console.log, I get "undefined".

The code is as follows:

export class Calendar {
    eventSource;
    viewTitle;

    constructor(private navController:NavController, private httpService:HttpService) {
        var classes = [];
        this.httpService.getCalendarConfig()
            .subscribe(res => classes => res);

        console.log(classes);
    }

Note, if I change .subscribe to:

    .subscribe(res => console.log(res));

It displays the JSON as it should in the console.

Edit: the httpService class looks as follows:

@Injectable()
export class HttpService {

    endpointUrl:string = '<address>';

    constructor(private http: Http) {}

    getCalendarConfig() {
        return this.http.get(this.endpointUrl + 'calendar.json')
                        .map(this.extractData)
                        .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || {};
    }

    private handleError(error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? '${error.status} - ${error.statusText}' : 'Server error';
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

}

Upvotes: 1

Views: 1278

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

Because you are considering that classes value to be applicable as soon as you make a call to service. But that wouldn't work with the way async calls works. They will always provide there output as soon as they ajax completes.

You will get the classes object inside success of the subscription of this.httpService.getCalendarConfig()

var classes = [];
this.httpService.getCalendarConfig()
    .subscribe(res => {
      classes => res;
      console.log(classes);
    });

Upvotes: 2

Related Questions