60

I new to Angular 2 still learning I am trying to hit a URL with a get call but the get doesn't seem to go through even in browser's network I cannot find that get URL being called.

The program is going to that method console logging above and below that get call but nothing for the get call

My service method

import { Headers, Http, Response } from '@angular/http';
import { Injectable } from '@angular/core';
import { Persons } from './mock-people';
import { Person } from './person';
import {Observable} from 'rxjs/Rx';

getAllPersons(): void {
  console.log("Here");
  this.http.get(`http://swapi.co/api/people/1`)
    .map((response: Response) => {
      console.log(response.json());
      response.json();
    });
  console.log("Comes here 2");
}

Imported HttpModule in app.module.ts

My console Screen shot

Console]

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110

4 Answers4

115

Http uses rxjs and is a cold/lazy observable, meaning that you should subscribe to it to make it work.

this.http.get(`http://swapi.co/api/people/1`)
  .map((response: Response) => {
    console.log(response.json());
    response.json();
  })
  .subscribe();

Or if you want to subscribe from somewhere else, you should return the http.get method like this:

getAllPersons(): Observable <any> {
  console.log("Here");
  return this.http.get(`http://swapi.co/api/people/1`)
    .map((response: Response) => {
      console.log(response.json());
      return response.json();
    });
}

and then :

getAllPersons().subscribe();
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
Milad
  • 27,506
  • 11
  • 76
  • 85
  • Thanks,but suppose if we donot call subscribe here but the calling method calls the subscribe why does it work then –  Dec 29 '16 at 14:07
  • The nest part was not error in console or anywhere :) –  Dec 29 '16 at 14:10
  • Thanks got it spend nearly 3-4 inorder to get this atlast had to post , there should have been some error to help me :) –  Dec 29 '16 at 14:14
  • When I was trying to resolve this issue I was getting response undefined and error undefined. Threw me until I found this answer. – Peter Marshall Jun 19 '17 at 09:25
  • @user7161814 , what you're asking is the same as saying : "I haven't subscribed to the newsletter, and I'm not getting any magazines on my doorstep, but there should be an error somewhere telling me something is wrong :":) – Milad Jul 04 '17 at 10:44
  • Need I use return in scuccess response: `response.json()`? – POV Aug 29 '17 at 12:28
  • I'm doing this as instructed, but still the response is undefined and getting a message "illegal return statement" even though the http get returns correctly according to Chrome and no actual errors are reported. – Starfleet Security Mar 04 '18 at 19:36
  • Thanks. Great. Why we must use the subscribe? – Jeeva J Mar 14 '18 at 02:14
  • @JeevaJsb https://stackoverflow.com/questions/44921788/what-is-subscribe-in-angular/44921830#44921830 – Milad Mar 14 '18 at 09:28
  • In my case, only the .suscribe() did the magic. I have been for two hours searching why my backend was not doing their job, and the problem was the frontend was not calling it. Thank you! – ermanitu Jun 10 '20 at 15:04
2

As mentioned by Milad in his answer, since Observables returned by Http's methods are cold/lazy and won't fire until you subscribe to them.

But let's say what if you don't want to .subscribe to the Observable but still want the HTTP request to fire?

In case you're using Angular 6 with Rxjs6 and don't want to subscribe , you can do the following:

...
import { publish } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {}

getAllPersons() {
  const getAllPersons$ = this.http.get(`https://swapi.co/api/people/1`)
    .pipe(
        publish()
      );

  getAllPersons$.connect();
}

Here's a Sample StackBlitz for your ref.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
1

method should return the response of api call using Observable.

service.cs

import { Http, Jsonp, Response, Headers, RequestOptions } from '@angular/http';
import { Injectable } from '@angular/core';
import { Persons } from './mock-people';
import { Person } from './person';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';

@Injectable()
export class Service {
  constructor(private jsonp: Jsonp, private _http: Http) { }

  getAllPersons():Observable<any>{
    console.log("Here");

    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers, method: 'get' });

    return this._http.get('http://swapi.co/api/people/' + personId)
        .map((res:Response) => {
            return <any>res.json();
        })
        .catch(this.handleError);          

    console.log("Comes here 2");
  }

  private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || ' error');
  }
}

options & headers are optional.

Note: instead of (<any>) you can define your datatype or any other defined type in which you get data in your response.

Thank You.

Amol Bhor
  • 2,322
  • 1
  • 12
  • 14
  • 2
    without Subscribe the call will not be made so after map subscribe is required either in this method or the calling method –  Dec 30 '16 at 06:08
  • @INFOSYS yes you are right. that we can do in component method were we call our service. – Amol Bhor Dec 30 '16 at 10:35
  • this._commonService.getPersonDetails(personId) .subscribe( data => { //code }, error => { this.ajaxLoader.completeLoading(); }, () => { this.ajaxLoader.completeLoading(); } ); – Amol Bhor Dec 30 '16 at 10:38
0

Note : Make sure to get response from app.js or some other backend services which is not hosted in same angular port we have to keep running both port . So better to use two terminal as I have used VS code terminal to keep running node server (http://localhost:3000/api/get) and used command prompt to keep running Angular server(http://localhost:4200)