链接帖子并使用Restangular解决问题

时间:2014-12-27 17:20:10

标签: angularjs restangular

我定义了一个Restangular服务:

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;
});

在一个解决方案中,我想调用一个POST,然后在POST响应的Location头中返回的URL上调用GET。 POST不需要任何参数。

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

我配置了一个响应提取器,将位置标头设置为POST请求的响应数据。

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;
});

我可以看到POST请求,它返回201并带有正确的Location头。但我没有看到GET请求。相反,我得到了这个例外:

 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)

1 个答案:

答案 0 :(得分:0)

创建服务时我犯了一个错误。我忘了在扩展它时返回model对象:

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;
});