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.

0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

@DilakshanSooriyanathan, Glad to here that , will you please also accept the answer?
1

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

.subscribe((res) => {

Comments

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');
    })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.