2

すべてのAngular Guruの皆さん、こんにちは。

私の質問は、あるサービス メソッドの戻り結果を他のメソッドに渡す方法です。または、簡単に言うと、サービスに認証メソッドがあり、これの戻りオブジェクトの結果はトークンです。トークンは、同じサービスに存在する残りの http 要求のヘッダーに追加するために使用されます。

例えば

私のサービス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);
    });
  }

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

2 つのサービス メソッドは 2 つのコントローラーで呼び出されます。私の拡張された質問は、あるコントローラーから別のコントローラーに $scope を渡す方法であり、ページが更新されても $scope 値が破棄されません。

それが理にかなっていることを願っています。

4

2 に答える 2

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;
            });
        }
    };
});
于 2013-08-22T07:19:52.237 に答える