简体   繁体   中英

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);
    }

}

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);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM