1

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

}

1 Answer 1

2

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);
    });
Sign up to request clarification or add additional context in comments.

5 Comments

Hi @Pankaj Parkar, thank you, that has improved the situation, as it no longer says "undefined". But now the console says: Array [ ]. Have I assigned to the wrong data type?
Could you please open that array.. you will get elements in it
Hi @Pankaj sorry for the delay! How do you open the array?
@JohnSmith please could you provide a plunkr?
I don't have a plunkr, but I've updated the post to show the full code. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.