0

I have written a simple service in angularJS. My service has two fields and one method.

What I want to know is how can I access these fields inside the method.

authToken has to be updated when the method authMethod is called. Simply not happening.

 app.service('userAuthenticationService',['$http','$q',function($http,$q){

//Authentication Method
this.authToken = '';
this.user = {};

this.authMethod = function(userObject) {

                var baseUrl = 'http://dev-api.nightoutloud.com/api/v1/accounts/login';
                var result =[];
                var requestObject = {
                        async: true,
                        crossdomain :true,
                        method: 'POST',
                        url: baseUrl,
                        headers: {
                        'Content-Type': 'application/json',

                        },
                        data:"{\n   \"phone_number\":\""+userObject.phoneNo+"\"\n}"
                };

                var loginPromise = function(resolve,reject){
                                      $http(requestObject).then(function(response){
                                                                  this.authToken = response.data.token;
                                                                  this.user = response.data.user;
                                                                  localStorage.loggedIn = 'yes';
                                                                  localStorage.user = this.user;
                                                                  localStorage.authToken = this.authToken;
                                                                  console.log(this.authToken,this.user);
                                                                  resolve(response);
                                                                },function(response){
                                                                  localStorage.loggedIn = 'no';
                                                                  reject(response);
                                                            });
                };

                return $q(loginPromise);
};
  • 1
    I'm guessing the `this` inside your promise resolution function no longer refers to the `this` in your service. Try adding `var _this = this;` to the top of your service and then use `_this` in place of `this` throughout your service. – Lex Sep 21 '16 at 23:09
  • works thanks ...this way of capturing scope is great – Nirbhay Gupta Sep 21 '16 at 23:27
  • @NirbhayGupta `this` isn't "scope". – Bergi Sep 22 '16 at 01:38
  • You really should avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572)! Just make it `return $http(requestObject).then(function(response) { …; return response }, function(err) { …; throw err })` – Bergi Sep 22 '16 at 01:39

0 Answers0