2015-06-11 74 views
0

如何在沒有從API響應錯誤處理角JS

service.js

app.factory('dropdownService', function ($http,CD_CONTEXT_VOLTAGE_URL) { 
    return { 
     getDropDownData: function (callback) { 
      $http.get(CD_CONTEXT_VOLTAGE_URL).success(callback); 
     } 
    } 
}); 

controller.js

app.controller('loadDropDownController', ['$scope','dropdownService',function($scope,dropdownService) { 

    getFormData(); 
    function getFormData() { 
     dropdownService.getDropDownData(function (results) { 
      $scope.contextlist = results.context; 
      $scope.cdlst = results.coordinationType; 
      $scope.voltageList = results.constraintValue; 

     }); 
    }; 
}]); 

上面的代碼只處理成功的條件我處理。有人可以幫助我的代碼,以便我可以處理錯誤條件

回答

1

如果您選中angular $http documentation,你會看到$ http.get()返回一個有.error()方法的承諾。那就是你給一些處理你錯誤的函數的地方。

app.factory('dropdownService', function ($http,CD_CONTEXT_VOLTAGE_URL) { 
return { 
    getDropDownData: function (callback) { 
     $http.get(CD_CONTEXT_VOLTAGE_URL). 
      success(callback). 
      error(errorCallback); 
    } 
} 

});

1

在你service.js

app.factory('dropdownService', function ($http,CD_CONTEXT_VOLTAGE_URL) { 
    return { 
     getDropDownData: function (callback, errorCallback) { 
      $http.get(CD_CONTEXT_VOLTAGE_URL) 
      .success(callback) 
      .error(errorCallback); 
     } 
    } 
}); 

雖然在controller.js

app.controller('loadDropDownController', ['$scope','dropdownService',function($scope,dropdownService) { 

    getFormData(); 
    function getFormData() { 
     dropdownService.getDropDownData(function (results) { 
      $scope.contextlist = results.context; 
      $scope.cdlst = results.coordinationType; 
      $scope.voltageList = results.constraintValue; 

     }, function(error){ 
    console.log('Error while getting response from the REST call'); 
}); 
    }; 
}]); 

這應該做的伎倆。

1

在您的服務中,您可以註冊.error callback()以及.success()回調。

的更新的代碼將是:

service.js

app.factory('dropdownService', function ($http,CD_CONTEXT_VOLTAGE_URL) { 
    return { 
     getDropDownData: function (successcallback,errorCallback) { 
      $http.get(CD_CONTEXT_VOLTAGE_URL) 
       .success(successcallback) 
       .error(errorCallback); 
     } 
    } 
}); 

controller.js

app.controller('loadDropDownController', ['$scope','dropdownService',function($scope,dropdownService) { 

    getFormData(); 
function getFormData() { 
    dropdownService.getDropDownData(function (results) { 
     $scope.contextlist = results.context; 
     $scope.cdlst = results.coordinationType; 
     $scope.voltageList = results.constraintValue; 

    },function(){ 
     //do something on error 
     }); 
}; 

}]);