Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 743
DHW Avatar asked Oct 23 '16 17:10

DHW


People also ask

What does HTTP GET return in angular?

get() request method. HttpClient. get() method is an asynchronous method that performs an HTTP get request in Angular applications and returns an Observable. And that Observable emits the requested data when the response is received from the server.

What is the return type of HTTP GET?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.

How would you write code to modify the response from an HTTP GET?

catch( (error: Response) => { return Observable. throw(error); } );

How do you pass multiple parameters in HTTP GET request in angular 8?

Passing multiple parameters to Http get request We have to pass page & per_page parameters to the list of users API. let queryParams = new HttpParams(); queryParams = queryParams. append("page",1); queryParams = queryParams. append("per_page",1);


1 Answers

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();
    });
}
like image 124
Günter Zöchbauer Avatar answered Sep 27 '22 22:09

Günter Zöchbauer