Angular 2 Http Get Response Example Angular 2 Http Get Response Example typescript typescript

Angular 2 Http Get Response Example


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


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


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