Angularjs承诺。控制器+服务不起作用

时间:2018-03-28 08:18:02

标签: javascript html angularjs

我只是想在我的应用中使用加载栏。我在像这样的angularjs中得到了服务

@PostConstruct
public void init() {
      LOGGER.info(" enabled :: " + enabled);

} //This prints true

在角度控制器中,我需要在服务(app.service('gethostsbyip', [ '$http', '$q', function($http, $q){ this.gethostsbyip = function(hostname, username, password){ var deffered = $q.defer(); var result = $http.post(REST_API_IP + 'discover?ip=' + hostname + '&username=' + username + '&password=' + password).then(function(resp){ deffered.resolve(result); location.href="#createvirtualization"; toastr.success('Your hosts, templates, networks have been updated!', 'Data was loaded!'); }).catch(function(e){ toastr.error('Some data in your form is incorrect. Please, try again!', 'Error!'); }); return deffered.promise; }; }]); )完成后将标志更改为false值。

当函数运行且没有错误时,标志会发生变化,但是如果服务出错,我需要更改标志。

gethostsbyip.gethostsbyip

2 个答案:

答案 0 :(得分:0)

then事件接受two参数。

app.controller('discoverCtrl', ['$scope', '$q', function($scope, $q) {

$scope.submitButt = function(hostname, username, password){
    if(!hostname || !username || !password){
    }
    else {
        $scope.flag = true;
        gethostsbyip.gethostsbyip(hostname, username, password)
        .then(
        // you currently have one callback in your `then` method
        function(res){
            $scope.test = false;
        }
        // solution
        , function(resForErrorCase){
            $scope.test = false;
        })
    .catch(function(e){
        $scope.test = false;
    })
  }
};

Promise definition reference

答案 1 :(得分:0)

如果发生错误,则拒绝承诺

.catch(function(e) {
  deffered.reject(e);
  toastr.error('Some data in your form is incorrect. Please, try again!', 'Error!');
});