使用已定义的方法更新单例对象的字段

时间:2016-09-21 22:34:53

标签: javascript angularjs constructor

我在angularJS中写了一个简单的服务。我的服务有两个字段和一个方法。

我想知道的是如何在方法中访问这些字段。

调用 authMethod 方法时,必须更新

authToken 。根本没有发生。

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

0 个答案:

没有答案