Search code examples
angulartypescriptangular-httpclient

Angular: HttpGet request leads to HttpErrorResponse


I am creating a Web Application with Angular and I want to send a HttpRequest using get to receive data from my api server.

This is my data client for http get:

import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  getData(url: string): Observable<any> {
    console.log("getting data from API with url: " + url);
    return this.http.get(url, { responseType: 'json' });
  }
}

And I call it through button click using:

this.dataService.getData(requestString).subscribe(
      (data: any) => {
        console.log(data);
      });

When I try it it get the error message:

ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: 'Unknown Error', url: '...', ok: false, …}

If I try the exact same url via postman it works and I get my result. Is there anything I am missing or that is wrong?


Solution

  • I figured it out. Actually I had 2 different problems:

    1. My launch.json was wrong. Since I launched on chrome I needed "--disable-web-security" runtime argument:
         {
                  "type": "chrome",
                  "request": "launch",
                  "name": "Launch Chrome against localhost",
                  "url": "http://localhost:4200",
                  "webRoot": "${workspaceFolder}",
                  "runtimeArgs": [
                    "--disable-web-security"
                  ]
            }
    
    1. Since my api usually takes a long time (~3min) to answer I also needed to add a longer timeout to the request:
        this.http.get(url, { responseType: 'json', headers: new HttpHeaders({ timeout: '300000' }) })