2016-06-23 2 views
2

Итак, у меня есть пара контроллеров и сервисов, которые функционируют правильно прямо сейчас, но мой босс хочет, чтобы я переместил блоки успеха/ошибки/окончательно от контроллера к сервису.Угловой JS - получение информации от службы

Контроллер Функция:

  $scope.createUserButton = function() { 
       $scope.isBusy = true; 
       creationService.makeNewUser($scope.form) 
       .success(function (data) { 
        var user = JSON.parse(data); 
        if (typeof user !== 'undefined') { 
         $scope.testusers.push(user); 
        } 

       }).error(function() { 
        notify({ 
         message: 'Could not create user', 
         classes: 'alert-danger', 
         templateUrl: 'partials/settingNotification.html' 
        }); 
       }).finally(function() { 
        $scope.isBusy = false; 
       }); 
      }; 

Услуги:

service('creationService', ['restfulRepo', '$http', 
function (restfulRepo, $http) { 
this.makeNewUser = function (tempuser) { 
    return $http({ 
     url: 'http://localhost:60098/***/*************/******', 
     data: tempuser, method: 'PUT' 
    }); 
}; 
}]); 

Проблема, что у меня в том, что если я перееду успех или, наконец, блоки к службе, то у них нет доступ к флагу isBusy или к массиву testusers. Массив привязан к графику в контроллере, который отображает переданную информацию.

+1

'$ http' возвращает обещание, в вашем контроллере вы можете сделать это:' creationService. makeNewUser(). then (function() {$ scope.isBusy = false;}); ' – Erevald

+1

https://docs.angularjs.org/api/ng/service/$http#!/« Предательство '$ http' обеим методам 'success' и' error' были устарели. Вместо этого используйте стандартный метод 'then'. Если' $ httpProvider.useLegacyPromiseExtensions' установлено в 'false', то эти методы будут вызывать ошибку' $ http/legacy'. " – Claies

ответ

2

С моим ответом, вы можете позволить привязки данных облегчить это для вас. Обратите внимание, как мы устанавливаем контроллер & - это переменные isBusy.

Контроллер:

$scope.isBusy = creationService.isBusy; //1-way Data Binding 
$scope.createUserButton = function() { 
      creationService.isBusy = true; 
      creationService.makeNewUser($scope.form).then(
        function(user){ 
         $scope.testusers.push(user); 
        }, function(error){ 
         notify({ 
         message: error, 
         classes: 'alert-danger', 
         templateUrl: 'partials/settingNotification.html' 
         }); 
        }); 

     }; 

Услуги:

service('creationService', ['restfulRepo', '$http', '$q', function (restfulRepo, $http, $q) { 
this.isBusy = false; 

this.makeNewUser = function (tempuser) { 
var defer = $q.defer(); 
    $http({ 
    url: 'http://localhost:60098/***/*************/******', 
    data: tempuser, method: 'PUT' 
    }).success(function (data) { 
       var user = JSON.parse(data); 
       if (typeof user !== 'undefined') { 
        defer.resolve(user); 
       }else{ 
        defer.reject("Undefined user"); 
       } 
      }).error(function() { 
       defer.reject('Could not create user'); 
      }).finally(function() { 
       this.isBusy = false; 
      }); 
    return defer.promise; 
    }; 
}]); 
+0

Мне пришлось внести небольшие изменения. Спасибо 'var defer = $ q.defer(); $ HTTP ({ URL: 'HTTP: // локальный: 60098/API/createTestUsers/CreateUser', данные: tempuser, метод: 'PUT' }). Успех (функция (данные) { вар пользователь = JSON .parse (данные); defer.resolve (пользователь); }) ошибка (функция() { уведомит ({ сообщения:. 'не удалось создать пользователь', классов: 'предупреждение-опасность', templateUrl: 'partials/settingNotification.html' }); }); return defer.promise; ' –

+0

Мое абсолютное удовольствие! –

0

В зависимости от того, какие обязанности несет служба. Это пример, если вы рассматриваете свою услугу как способ поговорить с сервером.

Контроллер несет ответственность за то, чтобы просто получать данные из службы и делать с ней что-то вроде привязки к просмотру или отображения сообщения об ошибке.

Услуги:

service('creationService', ['restfulRepo', '$http', 
    function (restfulRepo, $http) { 
     this.makeNewUser = function (tempuser) { 
      return $http({ 
       url: 'http://localhost:60098/***/*************/******', 
       data: tempuser, method: 'PUT' 
      }).then(function(){ 
       var user = JSON.parse(data); 
       return user; 
      }, function(e){ 
       //check server error response e to send the correct object to the controller 
       throw { 
        message: 'Could not create user', 
        classes: 'alert-danger', 
        templateUrl: 'partials/settingNotification.html' 
       }; 
      }); 
     }; 
    }]); 

Контроллер:

$scope.createUserButton = function() { 
    $scope.isBusy = true; 
    creationService.makeNewUser($scope.form) 
     .then(function (user) { 
      if (typeof user !== 'undefined') { 
       $scope.testusers.push(user); 
      } 
     }, function (e) { 
      notify(e); 
     }) 
     .finally(function() { 
      $scope.isBusy = false; 
     }); 
}; 
+0

wrapping '$ http' внутри' deferred' является анти-шаблоном, поскольку '$ http' уже возвращает обещание. – Claies

+0

@ Claies, что так верно. Позвольте мне изменить его. – gaheinrichs

+0

@Claies Я изменил ответ, чтобы вернуть обещание. – gaheinrichs

0

Похожие: Injecting $scope into an angular service function()

how do i pass scope from controller to service in angularjs?

Возможно, вам лучше всего переместить как ваши данные testusers, так и isBusy boolean в службу. Таким образом, все ваши другие контроллеры могут получить доступ к testusers и контролироваться переменной isBusy.

Сервис

service('creationService', ['restfulRepo', '$http', 
function (restfulRepo, $http) { 
this.testusers = []; // do whatever you want with it 
this.isBusy = false; 
this.makeNewUser = function (tempuser) { 
    return $http({ 
     url: 'http://localhost:60098/***/*************/******', 
     data: tempuser, method: 'PUT' 
    }); 
}; 
this.toggleBusy = function(){ 
    this.isBusy = this.isBusy ? false : true; 
}; 
this.createUserErr = function() { 
       notify({ 
        message: 'Could not create user', 
        classes: 'alert-danger', 
        templateUrl: 'partials/settingNotification.html' 
       }; 
this.createUserSuc = function (data) { 
       var user = JSON.parse(data); 
       if (typeof user !== 'undefined') { 
        this.testusers.push(user); 
       } 

      } 

}]); 

Контроллер

 $scope.createUserButton = function() { 
      creationService.toggleBusy(); 
      creationService.makeNewUser(creationService.createUserSuc) 
      .success().error(creationService.createUserErr); 
      }).finally(creationService.toggleBusy); 
     }; 
Смежные вопросы