我在Restangular的 .one()和 .put()功能方面遇到了问题。当我 Restangular.copy()我需要使用的元素时,我会丢失路径值。
如果我手动添加路径值,我会让它工作(例如下面的例子)。
我的计划是在 $ stateProvider 中使用解析,但这仍处于测试阶段,这就是我寻找建议/需要帮助的原因。
我做错了什么?
GET: /api/news/1
{
"success":true,
"status":200,
"data": [
{"id": 1, "title":"the title", "author":"the author", "date": 123456789, "contents": "the contents"}
]
}
'use strict';
angular.module('app', ['ui.router', 'restangular'])
.config(['RestangularProvider', '$stateProvider', function (RestangularProvider, $stateProvider) {
RestangularProvider.setBaseUrl('/api');
RestangularProvider.addResponseInterceptor(function (data, operation) {
var extractedData;
if (operation === 'getList') {
extractedData = data.data;
extractedData.success = data.success;
extractedData.status = data.status;
} else {
extractedData = data;
}
return extractedData;
});
$stateProvider.state('news', {
url: '/news/:id',
views: {
'articles': {
controller: 'NewsCtrl',
templateUrl: 'news-view.html'
}
}
});
}])
.controller('NewsCtrl', ['$stateParams', 'Restangular', function ($stateParams, Restangular) {
$stateParams.id = 1; // For the sake of this example
Restangular.one('news', $stateParams.id).get().then(function (data) {
console.log(data); // route set to news
var post = data.data[0]; // access the response object
post.title = 'a news title';
post.put(); // TypeError: undefined is not a function
var anotherPost = Restangular.copy(data.data[0]); // using Restangular.copy instead
anotherPost.title = 'another news title';
// anotherPost.route = 'news'; // if I add this to anotherPost, put() will work
anotherPost.put(); // /api/undefined/1 404 (Not found)
});
}]);
答案 0 :(得分:-1)
在使用方法
之前,您应该按照这些说明来改进实体的解析app.config(function(RestangularProvider) {
// add a response intereceptor
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
var extractedData;
// .. to look for getList operations
if (operation === "getList") {
// .. and handle the data and meta data
extractedData = data.data.data;
extractedData.meta = data.data.meta;
} else {
extractedData = data.data;
}
return extractedData;
});
});