Protagonist Protagonist - 27 days ago 7
JSON Question

Angular 2 method is not subscribing to the observable

I'm trying to get JSON data using a Service class.
Service class

import { Injectable }     from '@angular/core';
import { Http, HttpModule, Response } from '@angular/http';
import { GeneralTab }     from './generalTab';
import 'rxjs/Rx';
import { Observable }     from 'rxjs/Observable';


@Injectable()
export class GeneralTabService {
     constructor(private _http : Http) {

        console.log("Http call");
    }

getStatus(): Observable<any> {
    return this._http.get('http://samd.server.lan.at/taskmanagement/rest/taskconfigs/IND?language=EN&access_token=200')
         .map((res:Response) => <GeneralTab[]>res.json())
         .do(data => console.log("All: " +  JSON.stringify(data)))
.catch(this.handleError);

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


Component class

import { Component, OnInit } from '@angular/core';
import {GeneralTab} from "./generalTab";
import {GeneralTabService} from "./generalTab.service";
import { Observable } from 'rxjs/Observable';

@Component({
    selector: 'general-tab',
    templateUrl: '/general.component.html',
    providers : [GeneralTabService]

})

export class GeneralComponent implements OnInit{
    title = 'Serving data from General Component';

    errorMessage: any;
    status: GeneralTab [];
    mode = 'Observable';

    constructor (private generalService: GeneralTabService) {
        this.status = [];
    }

    ngOnInit() {
        console.log("Started");
        this.generalService.getStatus().subscribe(
            (status: any) => this.status = status,
            (error: any) =>  this.errorMessage = error
        );
        console.log(this.status);
    }

}


GeneralTab class

export class GeneralTab {

    constructor(public recipientId : string,
    public recipientName: string,
    public recipientFullname: string,
    public ouId:String,
    public ouName:String,
    public institute:number,
    public shortName:String,
    public status:String)
    {
    }
}


I see in the console that .do(data => console.log("All:" +  JSON.stringify(data))) is getting me JSON data like

{"subjectsConfig":[{"subject":"Client Data Maintenance","preselected":false,"initialDueDate":"2016-11-24","actionConfigs":[{"action":"SEND","recipients":[{"user":{"recipientId":"BD27A4F5923FCA13","recipientName":"ABTABT","recipientFullname":"ABTABT","ouId":"BD27A4F5923FCA13","ouName":"0015",....

Subscribe is not assigning any data to status array and I'm getting blank "status" array. I want this data as an array in status variable for testing purpose. How do I get?

Answer

If you log the response like

 console.log("Started");
 this.generalService.getStatus().subscribe(
         (status: any) => this.status = status,
         (error: any) =>  this.errorMessage = error
 );
 console.log(this.status);

Of course you will see a blank status since the above code(getStatus().subscribe) is async. Meaning you are making a request then you are waiting for the response inside subscribe and when it comes, you will assign status to this.status. While waiting you are already logging(this.status) which is initially blank.

Instead try this and check the log,

 console.log("Started");
 this.generalService.getStatus().subscribe(
       (status: any) => {
            this.status = status;
            console.log(this.status);
       },
       (error: any) =>  this.errorMessage = error
 );