Angular 2 Http Get Response Example

63,517

Solution 1

That's not supposed to work this way. When the data arrives the callback passed to the observable is called. Code that needs to access this data has to be inside the callback.

ngOnInit() {
    this.myHttp.getDataObservable(this.dataUrl).subscribe(
        data => {
          this.testResponse = data;
          console.log("I CANT SEE DATA HERE: ", this.testResponse);
        }
    );
}

update

getDataObservable(url:string) {
    return this._http.get(url)
        .map(data => {
            data.json();
            // the console.log(...) line prevents your code from working 
            // either remove it or add the line below (return ...)
            console.log("I CAN SEE DATA HERE: ", data.json());
            return data.json();
    });
}

Solution 2

Because http call is async. You need to make assignments in the subscribe function. Try like this:

this.myHttp.getDataObservable(this.dataUrl).subscribe(
            data => {
                      this.testResponse = data ;
                      console.log("I SEE DATA HERE: ", this.testResponse);
                     }
        );

Solution 3

Here is an easy to use sample that allows you to use promises.

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Config } from '../Config';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class Request {

    constructor(public http: Http)
    {

    }

    get(url): Promise<any>
    {
        return this.http.get(Config.baseUrl + url).map(response => {
            return response.json() || {success: false, message: "No response from server"};
        }).catch((error: Response | any) => {
            return Observable.throw(error.json());
        }).toPromise();
    }

    post(url, data): Promise<any>
    {
        return this.http.post(Config.baseUrl + url, data).map(response => {
            return response.json() || {success: false, message: "No response from server"};
        }).catch((error: Response | any) => {
            return Observable.throw(error.json());
        }).toPromise();
    }
}
Share:
63,517
DHW
Author by

DHW

Updated on January 19, 2020

Comments

  • DHW
    DHW over 4 years

    What is the correct way to get json data from an http get in Angular 2. I am working on testing some local data with a mocked endpoint, and I can see the result in the http.get() but I cannot assign it locally or there is some timing issue. Here is my simple service:

    import {Injectable} from '@angular/core';
    import {Http} from '@angular/http';
    import 'rxjs/add/operator/map';  // we need to import this now
    
        @Injectable()
        export class MyHttpService {
        constructor(private _http:Http) {}
    
        getDataObservable(url:string) {
            return this._http.get(url)
                .map(data => {
                    data.json();
                    console.log("I CAN SEE DATA HERE: ", data.json());
            });
        }
    }
    

    And here is how i'm trying to assign the data:

    import {Component, ViewChild} from "@angular/core";
    
    import { MyHttpService } from '../../services/http.service';
    
    @Component({
        selector: "app",
        template: require<any>("./app.component.html"),
        styles: [
            require<any>("./app.component.less")
        ],
        providers: []
    })
    export class AppComponent implements OnInit, AfterViewInit {
        private dataUrl = 'http://localhost:3000/testData';  // URL to web api
        testResponse: any;
    
        constructor(private myHttp: MyHttpService) {
        }
    
        ngOnInit() {
            this.myHttp.getDataObservable(this.dataUrl).subscribe(
                data => this.testResponse = data
            );
            console.log("I CANT SEE DATA HERE: ", this.testResponse);
        }
    }
    

    I can see the data I want in the get() call but I don't seem to have access to it after that call...please tell me what i'm doing wrong!

  • DHW
    DHW over 7 years
    Ok, thank you for the explanation i'm still new to Angular and how to correctly implement http calls. That being said, if I to handle the data in the callback like you show above, I still see:
  • DHW
    DHW over 7 years
    I CANT SEE DATA HERE: undefined
  • Günter Zöchbauer
    Günter Zöchbauer over 7 years
    The map(...)´ function needs to return the value, otherwise the subscriber won't get anything. If you remove the console.log... line, data.json() should implicitly return the result.
  • DHW
    DHW over 7 years
    Thank you for explaining it even further, removing the log call from the service resolved the issue as you said it would. I was unaware that call would have that affect on the response but it makes sense now. Thanks again....I see I still have plenty to learn.
  • Günter Zöchbauer
    Günter Zöchbauer over 7 years
    Yup, the result of the last expression is implicitly returned from the function if there is no explicit return. console.log() doesn't return anything, this is why you got undefined.
  • YYY
    YYY over 6 years
    How to use this.testResponse in .html page? {{testResponse }} this displaying as empty object.