DHW DHW - 1 month ago 19
TypeScript Question

Angular 2 Http Get Response Example

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!

Answer

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