Angular 2 Http Get Response Example
<p>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 <code>http.get()</code> but I cannot assign it locally or there is some timing issue. Here is my simple service:</p>

<pre><code>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 =&gt; {
                data.json();
                console.log("I CAN SEE DATA HERE: ", data.json());
        });
    }
}
</code></pre>

<p>And here is how i'm trying to assign the data:</p>

<pre><code>import {Component, ViewChild} from "@angular/core";

import { MyHttpService } from '../../services/http.service';

@Component({
    selector: "app",
    template: require&lt;any&gt;("./app.component.html"),
    styles: [
        require&lt;any&gt;("./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 =&gt; this.testResponse = data
        );
        console.log("I CANT SEE DATA HERE: ", this.testResponse);
    }
}
</code></pre>

<p>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!</p>