如何实现变量从一个服务方法传递到另一个服务方法

时间:2013-08-22 07:05:27

标签: angularjs

嗨,对所有角色大师,

我的问题是如何将一个服务方法的返回结果传递给其他方法。或者为了简化我在我的服务中有一个身份验证方法,返回对象的结果是一个令牌。该令牌将用于附加在我的标头中,用于驻留在同一服务上的其余http请求。

E.g

我的服务js

authenticatePlayer: function(postData) {
    return $http({
      method  : 'POST',
      url     : api + 'auth/player',
      data    : postData,
      headers : {'Content-Type' : 'application/json'}
    })
    .then(function(result) {
      return result.data.token; //this is now the token
    }, function (result) {
      console.log(result);
    });
  }

在服务js中,我有其他$ http请求,例如:

        getPlayerByEmail: function(email_address) {
        return $http({
            method  : 'GET',
            url       : api + 'player/' + email_address,
            headers : {'X-token': token} 
           //token here is from the authenticatePlayer method but how to get it??
        })
        .then(function(result) {
            return result.data;
        });
    }

两个服务器方法在两个控制器中调用,我的扩展问题是如何将$ scope从一个控制器传递到另一个控制器,即使页面刷新时,$ scope值也不会被销毁。

希望它有意义。

2 个答案:

答案 0 :(得分:4)

在控制器之间共享$ scope值的一种方法是创建一个service并将其注入您想要的任何控制器中;  示例服务,

angular.module('myApp', [])
    .service('shareScope', function () {

        return {
            get: function () {
                return value;
            },
            set: function(data) {
                value = data;
            }
        };
    });

在您的控制器中;

function Ctrl($scope, shareScope) {
    $scope.prop2 = shareScope.set('data');
    $scope.both = shareScope.get();
}

答案 1 :(得分:0)

将其存储在变量中:

angular.module('foo').factory('someService', function() {

    var token;

    return {
        authenticatePlayer: function(postData) {
            return $http({
                method  : 'POST',
                url     : api + 'auth/player',
                data    : postData,
                headers : {'Content-Type' : 'application/json'}
            })
            .then(function(result) {
                token = result.data.token; //this is now the token
            }, function (result) {
                console.log(result);
            });
        },
        getPlayerByEmail: function(email_address) {
            return $http({
                method  : 'GET',
                url       : api + 'player/' + email_address,
                headers : {'X-token': token} 
            })
            .then(function(result) {
                return result.data;
            });
        }
    };
});