2015-01-07 16 views
8

Ho un meccanismo di registrazione in cui la variabile rootscope viene inviata tramite il servizio. Dopo il successo aggiorna il campo $rootScope.success. Ma i servizi di angularjs sono dipendenti dalla callback. Il servizio aggiorna il rootscope.success ma la funzione esegue in sequenza il codice.Come gestire la richiamata in angularjs?

Come posso attendere che il servizio completi la risposta e quindi elaborare ulteriormente?

.controller('RegisterAccountCtrl', function ($scope,$rootScope,registerUser,$location) { 

    $rootScope.success = false; 
    $scope.registration = $rootScope.registration; 

$scope.getEnterGeneratedCode = function(){ 
     $rootScope.registration = $scope.registration; 
     registerUser.registerUser(); 
     if($rootScope.success){ 
      $location.path('/confirm'); 
     } 
} 

E il servizio

all'interno
.service('registerUser',function($http,$rootScope,$ionicLoading){ 
    this.registerUser = function(){ 
     $ionicLoading.show(); 
     $http({ 
      method: 'POST', 
      datatype:'json', 
      data:{obj:$rootScope.registration}, 
      url: 'http://localhost/LoginService.asmx/CreateUser', 
      contentType: "application/json; charset=utf-8", 
      cache: false 
     }).success(function (data, status, headers, config){ 
      if (status == '200') { 
       var obj = data; 
       $rootScope.success = true; 
       $ionicLoading.hide(); 
       //alert(obj); 
      } 
     }).error(function (data, status, headers, config){ 
      $ionicLoading.hide(); 
     }); 
    }; 

return this; 
}) 

risposta

6

Si desidera restituire la tua richiesta $http da registerUser che possono poi essere utilizzati nel controller nello stesso modo lo si utilizza nel servizio.

Controller:

registerUser.registerUser().success(function(data, status, headers, config){ 
    //This code will now execute when the $http request has resolved with a success 
    if($rootScope.success){ 
     $location.path('/confirm'); 
    } 
}).error(function(error, status, headers, config){ 
    //An error occurred in $http request 
    console.log(error); 
}); 

Servizio:

this.registerUser = function(){ 
    $ionicLoading.show(); 
    return $http({ 
     method: 'POST', 
     datatype:'json', 
     data:{obj:$rootScope.registration}, 
     url: 'http://localhost/LoginService.asmx/CreateUser', 
     contentType: "application/json; charset=utf-8", 
     cache: false 
    }).success(function (data, status, headers, config){ 
     if (status == '200') { 
      var obj = data; 
      $rootScope.success = true; 
      $ionicLoading.hide(); 
      //alert(obj); 
     } 
    }).error(function (data, status, headers, config){ 
     $ionicLoading.hide(); 
    }); 
}; 

Un paio di cose degne di nota ...

State ritornando da un servizio che non è richiesto, un servizio funziona come un'istanza e quindi l'istanza è già stata iniettata ed. È una fabbrica (singleton) che richiede un ritorno.

Si sta impostando $scope.registration ad essere lo stesso $rootScope.registration e quindi impostando $rootScope.registration ad essere lo stesso $scope.registration nella funzione getEnterGeneratedCode che è unnessasary e dovrebbe essere prototypicaly ereditata in ogni caso.

Si dovrebbe sempre cercare di depedencys definite con questo modo:

.controller('RegisterAccountCtrl', ['$scope', '$rootScope', 'registerUser', '$location', function($scope, $rootScope, registerUser, $location){ 

}]); 

A meno $rootScope.success viene utilizzato altrove la sua attualmente inutile impostare e consiglierei di evitare oggetti di scena di impostazione sul vostro $ rootScope come si può rapidamente uscire di controllo.

Ecco una versione semplificata del codice:

.controller('RegisterAccountCtrl', [ 
    '$scope', 
    '$rootScope', 
    'registerUser', 
    '$location', 
function($scope, $rootScope, registerUser, $location) { 

    $scope.getEnterGeneratedCode = function() { 
     $ionicLoading.show(); 
     registerUser.registerUser().success(function(data, status, headers, config) { 
      if (status == '200') { 
       var obj = data; 
       $ionicLoading.hide(); 
       $location.path('/confirm'); 
       //alert(obj); 
      } 
     }).error(function(data, status, headers, config) { 
      $ionicLoading.hide(); 
     }); 

    } 

}]) 

.service('registerUser', [ 
    '$http', 
    '$rootScope', 
    '$ionicLoading', 
function($http, $rootScope, $ionicLoading) { 

    this.registerUser = function() { 
     return $http({ 
      method: 'POST', 
      datatype: 'json', 
      data: { 
       obj: $rootScope.registration 
      }, 
      url: 'http://localhost/LoginService.asmx/CreateUser', 
      contentType: "application/json; charset=utf-8", 
      cache: false 
     }); 
    }; 

}]); 
+0

A meno che '$ rootScope .success' è usato al di fuori di questa chiamata, ora sembra non necessario. –

+0

Corretto, aggiungerò una versione semplificata aggiornata –

+0

@DavinTryon ha aggiunto una versione semplificata –

-1

Utilizzare una promessa - vedere i cambiamenti di seguito:

.controller('RegisterAccountCtrl', function ($scope,$rootScope,registerUser,$location) { 

    $rootScope.success = false; 
    $scope.registration = $rootScope.registration; 

$scope.getEnterGeneratedCode = function(){ 
     $rootScope.registration = $scope.registration; 
     registerUser.registerUser().then(function() { 
      $location.path('/confirm'); 
     }) 
} 

E il servizio all'interno

.service('registerUser',function($http,$rootScope,$ionicLoading){ 
    this.registerUser = function(){ 
     $ionicLoading.show(); 
     // Return a promise 
     return $http({ 
      method: 'POST', 
      datatype:'json', 
      data:{obj:$rootScope.registration}, 
      url: 'http://localhost/LoginService.asmx/CreateUser', 
      contentType: "application/json; charset=utf-8", 
      cache: false 
     }).success(function (data, status, headers, config){ 
      if (status == '200') { 
       var obj = data; 
       // Don't need now - $rootScope.success = true; 
       $ionicLoading.hide(); 
       //alert(obj); 
      } 
     }).error(function (data, status, headers, config){ 
      $ionicLoading.hide(); 
     }); 
    }; 

return this; 
}) 
+0

Cosa mi sono perso? Inoltre stai controllando $ rootScope.success al di fuori della tua callback asincrona. –

+1

Questo non funzionerà perché '$ rootScope.success' è controllato prima che sia impostato. –

+0

Credo di aver risposto alla sua domanda sul concatenamento dei comportamenti ma grazie per i downvotes su quella materia non correlata –

Problemi correlati