gpt4 book ai didi

javascript - Restangular.copy() : route on . one() 对象最终未定义

转载 作者:行者123 更新时间:2023-11-30 06:53:19 25 4
gpt4 key购买 nike

我在使用 Restangular 的 .one().put() 函数时遇到问题。当我 Restangular.copy() 我需要处理的元素时,我丢失了 route 值。

如果我手动添加 route 值,我就会让它工作(下面的示例)。

我的计划是在 $stateProvider 中使用解析,但这仍处于测试阶段,这就是我寻求建议/需要帮助的原因。

我做错了什么吗?


API 端:

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

}]);

最佳答案

在使用该方法之前,您应该按照这些说明改进实体的解析

https://github.com/mgonto/restangular#my-response-is-actually-wrapped-with-some-metadata-how-do-i-get-the-data-in-that-case

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

});

关于javascript - Restangular.copy() : route on . one() 对象最终未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26715998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com