Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Arrow function with brackets [duplicate]

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

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

Code 2

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

The key difference between these two code is that in Code 2 I placed the brackets after the 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.

like image 997
Victor Le Avatar asked Aug 02 '16 21:08

Victor Le


1 Answers

(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.

Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

like image 152
Rocket Hazmat Avatar answered Oct 20 '22 22:10

Rocket Hazmat