我正在使用离子(基于AngularJS框架)创建移动应用程序,我想在其中显示来自RESTfull API的数据。我对AngularJS很新,所以我不熟悉最佳实践。我想从这个API获取数据,但在URL中有一个周数参数,这样我就可以从特定周获取数据。我特别关注AngularJS website的例子。
这就是我服务中的内容:
var eventServices = angular.module('starter.services', ['ngResource']);
eventServices.factory('EventServiceAPI',['$resource',
function($resource) {
return $resource('http://localhost:8080/schedulingAPI/plannedevents?weeknumber=:weeknumber', {}, {
query: { method: 'GET', params:{weeknumber:'weeknumber'}, isArray: true}
});
}]);
这是我在控制器中获取API数据的原因:
$scope.events = EventServiceAPI.get({weeknumber: 7});
但是,我仍然会收到错误:
Error: [$resource:badcfg] object
当我在服务中使用完整的API URL并在我的控制器中使用$scope.events = EventServiceAPI.query()
时,会显示完整的API数据而不会出错。
我也没有把参数放在哪里;在资源URL或查询方法中的params选项之后的括号中。
修改
http://localhost:8080/schedulingAPI/plannedevents?weeknumber=:weeknumber
[{"id":2985,"event":{"eventId":589,"subject":"Masterproef","year":2014,"weekNumber":7,"dayNumber":6,"startHour":8,"startMinute":10,"endHour":12,"endMinute":45,"startTime":"2014-02-14T07:10:00Z","endTime":"2014-02-14T11:45:00Z","classgroups":[{"id":8,"name":"4ELICTI"},{"id":4,"name":"4ENAU"},{"id":10,"name":"4ELICTE"},{"id":1,"name":"4CHB"},{"id":3,"name":"4ENEL"},{"id":9,"name":"4EMEM"},{"id":2,"name":"4CHC"},[]],"teacher":null},"rooms":[{"id":24,"abbr":"D015"}]},{"id":4021,"event":{"eventId":604,"subject":"Bedrijfsbeleid 2 hc","year":2014,"weekNumber":7,"dayNumber":6,"startHour":8,"startMinute":10,"endHour":9,"endMinute":35,"startTime":"2014-02-14T07:10:00Z","endTime":"2014-02-14T08:35:00Z","classgroups":[{"id":6,"name":"4ELICT"},[]],"teacher":null},"rooms":[{"id":44,"abbr":"G120"}]}]
答案 0 :(得分:2)
将params:{weeknumber:'weeknumber'}
替换为params:{weeknumber:'@weeknumber'}
,注意@
。
如果参数值以@为前缀,那么该值的值 参数是从数据对象中提取的(对非GET有用) 操作)。
使用查询调用您的函数:
$scope.events = EventServiceAPI.query({weeknumber: 7});
实际上,您可以像这样简化资源声明:
eventServices.factory('EventServiceAPI',['$resource',
function($resource) {
return $resource('http://localhost:8080/schedulingAPI/plannedevents');
});
}]);
Angular会自动为您附加查询字符串