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?
tap? Simply subscribe to thegetwithout usingpipeor anything.this.http.get('...').subscribe(p => { console.log(p) });- Noémi SalaüngetUsers()? technically this code should work - LLaitapis an alias ofdo, so it shoud not mess with your observable. Can you create a plunker to reproduce this behavior ? - Noémi Salaünreturnbeforethis.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