Viet Le Viet Le - 6 months ago 42
Javascript Question

ES6 Fat Arrow function with brackets

I came across a little problem in my code which was kind of confusing to me and hope someone could explain why it does the things it does.

Code 1

return this.http.get('/api')
.map((response:Response) => response.json());

Code 2

return this.http.get('/api').map((response:Response) => {

The key difference between these two code is that in Code 2 I placed the brackets after the fat arrow function to add my tasks inside those brackets and in Code 1 I took the brackets out and place the task on one line.

My question is why does my object coming from the server side coming back as undefined in Code2 with the subscribe method that angular2 provided while Code1 returns the object I suspect.

(response:Response) => response.json()

This is shorthand for this:

(response:Response) => { return response.json(); }

The {} let you add multiple statements inside the block. Without them, the function just runs the one statement and returns its value.