2016-03-30 23 views
0

kodunda zaman uyumsuz olarak yürütme Angular.js'yi kullanmayı öğreniyorum ve REST benzeri bir API kullanarak kendi kimlik doğrulama kodumu yazmayı denedim. Aşağıda kimlik doğrulama servisimin kodu yer almaktadır.JavaScript

signIn işlevimle ilgili sorun, api'mim HTTP 200 döndüğünde bile her zaman false döndürmesidir. Bir süre sonra, javascript'inifadesinin response = res.data.key; ifadesinden önce yürütüldüğünden dolayı eşzamanlı doğasından kaynaklandığını anladım.

Ödev tamamlandıktan sonra return ifadesini nasıl uygulayacağımı bilmiyorum (yanıt HTTP 200 ise). Bunu nasıl yaparım?

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

cevap

2

Kullanım $q.defer(): Artık

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

, yapabileceğiniz:

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

Vaatler hakkında bilgi edinmeniz gerekir: söz vermeyi http iletisinden döndürün.

This may help