Search code examples
angularjsrestangular

Chaining post and get in resolve with Restangular


I defined a Restangular service:

var dashboards = angular.module('models.dashboards', ['restangular']);

dashboards.factory('Dashboards', function(Restangular) {
    var Dashboards = Restangular.service('dashboards');
    Restangular.extendModel('dashboards', function (model) {
        //model.newMethod = function() {
        //}
    });
    return Dashboards;
});

In a resolve, I want to call a POST followed by a GET on the URL returned in the Location header from the POST response. The POST does not need any parameter.

resolve: {
    'drafts': ['Dashboards', function (Dashboards) {
        return Dashboards.post().then(function(result) {
            return Dashboards.oneUrl('newDash', result.data).get();
        });
    }]
},

I configured a response extractor to set the location header into the response data for POST request.

RestangularProvider.setFullResponse(true);

RestangularProvider.setResponseExtractor(function(data, operation, route, url, response, deferred) {
    var returnData = data;

    if(operation === 'post') {
        console.log(response.headers());
        returnData = response.headers().location;
    }

    return returnData;
});

I can see the POST request which returns 201 with a correct Location header. But I don't see the GET request. Instead I get this exception:

 TypeError: Cannot set property 'singleOne' of undefined
    at $get.okCallback (restangular.js:1145)
    at processQueue (ionic.bundle.js:20962)
    at ionic.bundle.js:20978
    at Scope.$get.Scope.$eval (ionic.bundle.js:22178)
    at Scope.$get.Scope.$digest (ionic.bundle.js:21994)
    at Scope.$get.Scope.$apply (ionic.bundle.js:22282)
    at done (ionic.bundle.js:17439)
    at completeRequest (ionic.bundle.js:17629)
    at XMLHttpRequest.requestLoaded (ionic.bundle.js:17570)

Solution

  • I made a mistake when creating the service. I forgot to return the model object when extending it:

    var dashboards = angular.module('models.dashboards', ['restangular']);
    
    dashboards.factory('Dashboards', function(Restangular) {
        var Dashboards = Restangular.service('dashboards');
        Restangular.extendModel('dashboards', function (model) {
            //model.newMethod = function() {
            //}
            return model;
        });
        return Dashboards;
    });