1

I have a http post function.

login(){

    var data = {
      email : this.name,
      password : this.pass,
      appId : this.appId
    };
    console.log(data);

    this.http.post(SERVER_URL+"/templatesAuth/authenticateForApp",data)
      .subscribe(function(res){

         let requestParams = {
            "token": res.token,
            "email": data.email,
            "name": res.user.name,
            "phone": res.user.phone,
            "streetNumber": res.user.streetNumber,
            "streetName": res.user.streetName,
            "country": res.user.country,
            "city": res.user.city,
            "zip": res.user.zip,
            "type": 'internal',
            "appId":res.user.appId,
            "registeredUser": res.user.sub
          };


        },
        function(err){
          alert('login failed');
        })


  }

inside the function(req){ } I cannot write or use calls like examplearray.push(); im always having an error Cannot read property 'push' of undefined

when I use Local storage functions like.

this.localStorageService.set('test'+this.appId,(requestParams));

error : Cannot read property 'set' of undefined

but I can use them out side of the function(req){ }. couldn't figure-out the problem

is there any way to get the requestParams outside.

3 Answers3

5

This is very common issue of scoping :

Just change the line

.subscribe(function(res){

to

.subscribe((res) => {

Another way of doing is :

.subscribe(function(res){ ... }).bind(this)

Great article to read : https://toddmotto.com/es6-arrow-functions-syntaxes-and-lexical-scoping/ and check this answer for : Difference between arrow function and bind()

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
1

You should use arrow function .When using arrow functions,property is not overwritten change it as,

.subscribe((res) => {
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

Try this

this.http.post(SERVER_URL+"/templatesAuth/authenticateForApp",data)
  .subscribe((res) => {

     let requestParams = {
        "token": res.token,
        "email": data.email,
        "name": res.user.name,
        "phone": res.user.phone,
        "streetNumber": res.user.streetNumber,
        "streetName": res.user.streetName,
        "country": res.user.country,
        "city": res.user.city,
        "zip": res.user.zip,
        "type": 'internal',
        "appId":res.user.appId,
        "registeredUser": res.user.sub
      };


    },
    function(err){
      alert('login failed');
    })
}
Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51