Yifan Yifan - 1 year ago 81
Javascript Question

Angular 2, localhost/null error when trying to use http.get?

I am using Angular 2 to make a webpage. When I load the page, I use OnInit to run the following method (with generic names substituted):

getAllObjects(): Promise<object[]>{
return this.http.get(this.getAllObjectsUrl).toPromise().then(response => response.json().data).catch(this.handleError);

I've verified in my browser that the getAllObjects url does indeed return an array of
in JSON format. Here is the url if it is helpful:

private getAllObjectsUrl : '';

However, this method triggers the handleError catch and the browser's debugging log shows
GET localhost:3000/null 404 NOT FOUND
(I am using an npm server to run it, hence the localhost).

I do not believe it is a CORS issue because I downloaded the Chrome CORS plugin and other API calls have worked. It is only this particular API url that is causing a problem, which I find strange as my other API calls work and they follow the exact same format (except a different url).

I thought maybe the
wasn't allowed an OnInit, but I replaced
with a different working API call, and I didn't receive this error.

I am completely stuck and any help would be appreciated (could this error be because of the web API, not the front end?).

Answer Source

getAllObjectsUrl doesn't contain the url because you are using colon(:) instead of equal sign(=)

Colon indicates the type of the variable, whereas equal sign initializes it.

change this

private getAllObjectsUrl : '';

for this

private getAllObjectsUrl = '';