Rosenberg
Rosenberg

Reputation: 2454

Angular 6 - Accessing variable outside function not working

export class EditClientComponent implements OnInit {

 apiEndPoint: 'http://localhost:1337/upload';

 fileChange(event) {
 //...
    this.http.post(`${this.apiEndPoint}`, formData, httpOptions)
 //...
 }
}

I get a weird error:

status: 404, statusText: "Not Found", url: "http://localhost:4100/undefined"...

Which means that it's not reading apiEndPoint at all, and if I replace ${this.apiEndPoint} with the actual url, it works.

What can I do?

Upvotes: 1

Views: 809

Answers (3)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24454

In here apiEndPoint: 'http://localhost:1337/upload'; is statement of declare the type of apiEndPoint to string literal and it is initial value is undefined.

Just fixed to this

apiEndPoint:string = 'http://localhost:1337/upload';

Upvotes: 1

Osakr
Osakr

Reputation: 1066

In addition to the above reply. You don't need to format a string if you already have the full value of the URL in the var. Instead of this: ${this.apiEndPoint}. Simply do:

this.http.post(this.apiEndPoint, formData, httpOptions)

Upvotes: 1

Raed Khalaf
Raed Khalaf

Reputation: 2065

change the declaration of apiEndPoint to = instead of :

apiEndPoint = 'http://localhost:1337/upload';

you are specifying the type of the variable not an initial value.

Upvotes: 5

Related Questions