2016-03-30 11 views
0

現在、Angular.jsの使い方を学習しており、RESTのようなAPIを使用して自分の認証コードを書き込もうとしています。以下は私の認証サービスのコードです。JavaScriptでコードを非同期で実行する

私のsignIn関数の問題は、私のAPIがHTTP 200を返しても常にfalseを返すということです。しばらくしてから、は、response = res.data.key;ステートメントの前にreturn response;ステートメントが実行されているというJavaScriptの同期的な性質のためであるとわかりました。

割り当てが完了した後でreturn文を実行する方法がわかりません(応答がHTTP 200の場合)。これはどうすればいいですか?

angular.module('app').factory('auth', ['Base64', '$http', function(Base64, $http) { 
    return { 
     signIn: function(email, password) { 
      var response = false; 
      var encoded = Base64.encode(email + ':' + password); 
      $http.defaults.headers.common.Authorization = 'Basic ' + encoded; 
      $http.post('api/v1/sign_in', {}).then(function(res) { 
       if (res.status == 200) { 
        response = res.data.key; 
       } 
      }); 
      return response; 
     }  
    } 
}]); 

答えて

2

使用$q.defer():今

angular.module('app').factory('auth', ['Base64', '$http', '$q', function(Base64, $http, '$q') { 
    return { 
     signIn: function(email, password) { 
      var response = false; 
      // You create a deferred object 
      // that will return a promise 
      // when you get the response, you either : 
      // - resolve the promise with result 
      // - reject the promise with an error 
      var def = $q.defer(); 
      var encoded = Base64.encode(email + ':' + password); 
      $http.defaults.headers.common.Authorization = 'Basic ' + encoded; 
      $http.post('api/v1/sign_in', {}).then(function(res) { 
       if (res.status == 200) { 
        response = res.data.key; 
        // success: we resolve the promise 
        def.resolve(response); 
       } else { 
        // failure: we reject the promise 
        def.reject(res.status); 
       } 
      }); 
      // You return the promise object that will wait 
      // until the promise is resolved 
      return def.promise; 
     }  
    } 
}]); 

、あなたが行うことができます:

auth.signIn().then(function(key) { 
    // signin successful 
    // do something with key 
}).catch(function(err) { 
    // signin failed :(
    // do something with err 
}).finally(function() { 
    // you could do something in case of failure and success 
}) 
2

約束について学ぶ必要があります:http投稿から約束を返してください。

This may help

関連する問題