-1

I found this code online and can't seem to understand its purpose. Why is the .map method called twice, are the res variable the same in both method?

login(email, password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return this.http
      .post(
        '/login', 
        JSON.stringify({ email, password }), 
        { headers }
      )
      .map(res => res.json())
      .map((res) => {
        if (res.success) {
          localStorage.setItem('auth_token', res.auth_token);
          this.loggedIn = true;
        }

        return res.success;
      });
  }
LoïcR
  • 4,940
  • 1
  • 34
  • 50
Anna Lee
  • 909
  • 1
  • 17
  • 37

1 Answers1

2

The operator => is a lambda expression, it's just a short version of a function. For example, the code a => a * 10 is the exact same thing as

function (a) {
    return a * 10;
}

The map function is comming from RxJS, you can check the documentation about it here. It, basically, just "update" the value of the returned value. These two variable are the same, just updated with the previous operation.

Basically, your code is making a POST request to the URL /login with a JSON containing the email and the password. It then edit the result from this request to a JSON, and with the result, it's checking if the value of res.success is true, if yes, you are storing the auth_token in the localStorage. Otherwise, you are just continuing the script and return the value of res.success.

LoïcR
  • 4,940
  • 1
  • 34
  • 50
  • I see thank you so much, so, .map(res => res.json()) means the response is converted into json format and then saved into 'res'. If the 'res' in the res.json() means Response, it does not need to be defined before this code? I did not see any 'res' before this code. so, I was not that clear. This json formatted 'res' has auth_token key inside? Thank you again. – Anna Lee Dec 02 '16 at 14:13
  • Yep, it's exactly this. – LoïcR Dec 02 '16 at 14:14
  • thank you, so, is it correct in res=> res.json(), the first res has the json formatted value while the second res is 'Response'? – Anna Lee Dec 02 '16 at 14:18
  • The first res is the parameter, it contains the original res, then you are applying the json filter on type, and re-assigning the new value to the initial res. – LoïcR Dec 02 '16 at 18:46