Protagonist Protagonist - 1 year ago 83
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';

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

        console.log("Http call");

getStatus(): Observable<any> {
    return this._http.get('')
         .map((res:Response) => <GeneralTab[]>res.json())
         .do(data => console.log("All: " +  JSON.stringify(data)))

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';

    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() {
            (status: any) => this.status = status,
            (error: any) =>  this.errorMessage = error


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 Source

If you log the response like

         (status: any) => this.status = status,
         (error: any) =>  this.errorMessage = error

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,

       (status: any) => {
            this.status = status;
       (error: any) =>  this.errorMessage = error
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download