Search code examples
angularjsevent-handlingangular-resource

Angular: $resource is returning null response error on bad url


My usage of $resource is able to capture errors only if they are returned by the server, like bad login etc. However, any other errors like bad url etc. are being swallowed up by Angular itself, without bubbling up to my exception handler.

See the demo.

Click on the login button, alert shows but response object has nothing in it. Yet, console log shows the error.

Here is the code

    (function() {
  "use strict";
  function userAccount($resource) {
    return {
      login: $resource("http://lab2/Token", {}, {
        'loginUser': {
          method: 'POST'
        }
      })
    };
  }
  angular.module("mymod", ["ngResource"])
    .factory("userAccount", ["$resource",
      userAccount
    ])
}());

(function() {
  "use strict";

  function homeCtrl(userAccount) {
    var vm = this;
    vm.test = "My test";
    var obj = {
      user: "usera",
      password: "secret"
    };
    vm.login = function() {
      userAccount.login.loginUser(
        obj,
        function(data) {
          console.log("Yes");
        },
        function(response) {
          alert("Bad" + response.data.error_description);
        });
    }
  }
  angular.module("mymod").controller("homeCtrl", ["userAccount", homeCtrl]);
}());

Solution

  • please check this link and look for $promise

    here's an example:

    vm.login = function() {
      userAccount.login.loginUser(obj).$promise.then(
          function (response) {
             // todo response;
           }, function (reason) {
             //todo reason;
       });
    };