5

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.

Mulan
  • 129,518
  • 31
  • 228
  • 259
Victor Le
  • 1,758
  • 3
  • 17
  • 25

1 Answers1

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

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • You're welcome. Also, can you clear something up for me? Why do you have `response:Response` instead of just `response`? Is that like a type hint or something? – gen_Eric Aug 02 '16 at 21:32
  • Uhmm from what the tutorial told me. It is a typescript syntax that ensures me that it is of type Response. So future errors are avoided. Don't take my word for granted though lol I'm still learning. Is it unnecessary? – Victor Le Aug 02 '16 at 21:33
  • It may be necessary in Typescript, I don't know, I've never used it. In JavaScript, it's a syntax error. – gen_Eric Aug 02 '16 at 21:39