使用angularjs的service $resource从restful api中检索数据

Retrieve data from restful api with angularjs service $resource

本文关键字:api restful 检索 数据 resource angularjs service 使用      更新时间:2023-09-26

我尝试使用$resource服务与surveygizmo api。
我的代码:

html:

<div ng-app="Survey">
<body>
<div ng-controller="SurveyCtrl">
    {{survey.data.title}}
</div>
</body>
</div>

my script:

angular.module('Survey', ['ngResource']);
function SurveyCtrl($scope, $resource) {
    $scope.surveygizmo = $resource('https://restapi.surveygizmo.com/v3/survey/:id',
        {id: '@id'},
        {get:{method:'JSONP', params: {'user:pass':'xxx@xxxx:xxxx', q:'angularjs', callback:'JSON_CALLBACK'}, isArray:true}});
$scope.survey = $scope.surveygizmo.get({id:xxxx}, function(survey) {
        alert('this is ok');
    }, function(err){
        alert('request failed');
    });
}

当我尝试时,警告"请求失败"出现在我的页面上。没有json结果的页面,但我可以看到它在firebug网络菜单。
我能错过什么吗?
kalaoke

我知道这个问题很老了,但我想我也许能帮上忙。我在SurveyGimzo工作。我们确实支持JSONP, JSON和XML。然而;为了请求JSONP,您需要在url中指定它。使用您的示例URL,它看起来像这样。

https://restapi.surveygizmo.com/v3/survey/:id.jsonp

现在,当你请求JSON_CALLBACK作为你get动作的ngResource参数的一部分时,你会得到一个正确包装的对象。

我一直在使用SG REST api修补一个minnie AngularJS应用程序。你可以看看我的github https://github.com/sfisherGizmo/ang-app

我希望这对其他可能遇到这种情况的人有所帮助。

Survey Gizmo不支持JSONP。Survey Gizmo支持的HTTP方法有放,发,删除看到http://developer.surveygizmo.com/rest-api-documentation/methods/

或者如果他们支持,他们没有在API文档中指定。

这是当你将.get改为.query时我看到的结果

Request URL:https://restapi.surveygizmo.com/v3/survey/xxxx
Request Method:OPTIONS
Status Code:200 OK

如果你继续使用。get,响应是

Request URL:https://restapi.surveygizmo.com/v3/survey/xxxx
Request Method:GET
Status Code:200 OK

但是响应没有封装在JSONP回调中。虽然你可以在firebug的网络控制台中看到一个响应,但是angular无法打开它,因为它不是JSONP响应。

查看http://jsfiddle.net/jhsousa/aQ4XX/中使用ngResource的angularjs示例