Angular 2 http get not getting

2019-01-01 01:25发布

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]

3条回答
琉璃瓶的回忆
2楼-- · 2019-01-01 01:37

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();
查看更多
君临天下
3楼-- · 2019-01-01 01:46

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.

查看更多
姐姐魅力值爆表
4楼-- · 2019-01-01 01:48

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.

查看更多
登录 后发表回答