Search code examples
javascriptangularjsasp.net-web-apiangularjs-scopeangularjs-service

How getting the ErrorMessage from Service in AngularJS?


I don't know how I access the error message from the service. I'm using WebAPI2 and AngularJS.

Controller:

testApp.controller('ModalCtrl', ['$log', '$scope', '$modalInstance', '$rootScope', 'CrudService',
    function ($log, $scope, $modalInstance, $rootScope, CrudService) {
    $scope.updateItem = function (updateItem) {
       CrudService.update(updateItem)
          .success(...)
          .error(function (data) { //doesn't work: CrudService.update(...) is undefined
              $scope.dataError = data.ModelState 
          });
       $scope.ok();
    }

Service:

testApp.factory('CrudService', ['$log', 'resService',
    function ($log, resService) {
    return {
       ...
       update: function (updateItem) {
          updateItem.$update().then(function (response) {
              //SUCCESS MESSAGE definieren
          }, function (response) {
              $log.info('Update ERR:', response.data.ModelState); //Here I'm getting the error messages
              var dataError = []; 
              dataError = response.data.ModelState; //How can I use this in the Ctrl?
          });
       },
    ...

Resource service:

return {
   name: $resource(baseUrl + '/api/name/:Id', {
      Id: '@Id'
   }, {
      'update': {
         method: 'PUT'
      }
   }),

I want to use the variable "dataError" as $scope in the Ctrl. How can I do this?


Solution

  • return {
       ...
       update: function (updateItem) {
          return updateItem.$update();
       },
    
    $scope.updateItem = function (updateItem) {
       CrudService.update(updateItem).then(
          function(resp){
    
          },
          function(error){
            $scope.dataError = error.data.ModelState;
         }
    
       );
    }
    

    UPDATE

    Factory (unlike service) isn't returning something automatically.
    You need to return like that. (or return your function wich contains another return)

    testApp.factory('CrudService', ['$log', 'resService',
        return {
           ...
           update: function (updateItem) {
              updateItem.$update().then(function (response) {
                  //SUCCESS MESSAGE definieren
              }, function (response) {
                  $log.info('Update ERR:', response.data.ModelState); //Here I'm getting the error messages
                  var dataError = []; 
                  dataError = response.data.ModelState; //How can I use this in the Ctrl?
              });
           },
        ...