Search code examples
javascriptangularjscoffeescript

Angular $resource always calls success callback


I have an issue with Angular $resource. I use it with our API server with CORS enabled.

No matter what error code server returns (tried 500, 422, 409) resource always calls success callback.

Action in the controller:

@SpacePostsService.save { spaceId: @space._id }, @post, @_createSuccess, (errors)=>¬
  @_createError(errors, form)

Where SpacePostsService:

SpacePostsService = $resource postsUrl, {},¬
  query:¬
    isArray: true¬
    method: 'GET'¬
    responseType: 'json'¬
    transformResponse: (data, headers)->¬
      results = data.results || data¬
      results = [results] unless _.isArray(results)¬
      results

Does anyone have an idea what I am doing wrong?

PS. For readability purposes I didn't show all the code, SpacePostService is a factory and it's properly injected in to the controller.


Solution

  • Finally I've found the issue. It turns out I had global interceptor defined in other place:

    AjaxInProgress =
      request: (config)->
        $rootScope.$broadcast 'ajax:in-progress'
        config
      response: (response)->
        $rootScope.$broadcast 'ajax:finished'
        response
      responseError: (response)->
        $rootScope.$broadcast 'ajax:finished'
        return response
    

    The last line in responseError method is the most important one - because I didn't reject the promise so Angular thought I recovered from error and it called success callback in the $resource function. I changed last line in the AjaxInProgress to:

    responseError: (response)->
        $rootScope.$broadcast 'ajax:finished'
        $q.reject(response)
    

    It solved the problem.

    Thank you guys for your help.