0
votes

I just created an Angular app using the angular/cli and following their tutorial. Then I decided to include http get request using observables and a real rest API and noticed that angular was always getting null. I tried with several public rest APIs (they do return json objects when I put the URL in a browser) however when I console log the object returned it is always null. This is the last code of my service using a public API:

import { Injectable } from '@angular/core';
   import { Observable } from 'rxjs/Observable';
   import { of } from 'rxjs/observable/of';
   import { HttpClient, HttpHeaders } from '@angular/common/http';
   import { catchError, map, tap } from 'rxjs/operators';

   @Injectable()
   export class myService {

   private apiURL= 'https://jsonplaceholder.typicode.com/users';
    constructor(private http: HttpClient) { }


    getUsers() {
      console.log('calling get!');
      this.http.get('https://jsonplaceholder.typicode.com/users').pipe(
              tap(users => console.log(users))).subscribe(p => {console.log(p);});
      console.log('calling get finish!');  
     }
    }

Any ideas?

1
Why are you using tap ? Simply subscribe to the get without using pipe or anything. this.http.get('...').subscribe(p => { console.log(p) }); - Noémi Salaün
How are you calling getUsers()? technically this code should work - LLai
Ok nevermind, tap is an alias of do, so it shoud not mess with your observable. Can you create a plunker to reproduce this behavior ? - Noémi Salaün
It always returns undefined (and not null), because your method doesn't return anything. Add return before this.http.get(.... And remove the call to subscribe(). The component must subscribe, not the service. And to be able to access external APIs using AJAX, they need to enabled CORS. If they don't, you won't be able to access them (whether or not it works by pasting the URL in the browser location bar). - JB Nizet
Do you see the request being done in your devtools networks tab? How are you invoking this function? Please add a minimal example of your situation - Jota.Toledo

1 Answers

0
votes

Thanks everyone for the answers! The issue seems to be related to the browser we were using to test the call (Chrome Canary v65.0.3309.2 with security disabled to allow cross origin requests). We changed the config to run the app in other browsers and the HttpClient is working fine now... -.-