How to pass json object to WebApi as GET using $resource in angular?
My service:
pmsService.factory('Widgets', ['$resource', function ($resource) {
var data = $resource('/api/:path/:id', {
path: '@path'
}, {
getWidgets: {
params: { path: 'widgets' },
method: "GET",
isArray: true
},
getWidget: {
params: { path: 'widgets' },
method: "GET",
isArray: false
},
getWidgetData: {
params: { path: 'widgets' },
method: "POST"
},
});
return data;
In angular controller:
Widgets.getWidgetData({ id: $scope.widget.id}, $scope.paramValues ).$promise.then(function (data) {
$scope.widget.Data = data;
$log.debug($scope.widget.Data);
});
In Controller:
[Route("api/widgets/{id}")]
[HttpPost]
public Object Get(int id, dynamic prms)
{
....
}
This should sends 2 parameters to WebApi Controller, id and list of parameters for the Widget. Fiddler shows:
/api/widgets/31/%5Bobject%20Object%5D
So routing works correctly, but the object prms I received is empty.
I don't really understand what you're trying to do there but if you're trying to achieve a url parameter as in /api/widgets/31?foo=bar
, then this is how I would do it.
angular
.module('myMod', ['$resource'])
.factory('Widgets',
['$resource', function ($resource) {
return $resource(
'/api/:path/:id/',
{'path': '@path'},
{
getWidgets: {
params: {path: 'widgets'},
method: "GET",
isArray: true
},
getWidget: {
params: {path: 'widgets'},
method: "GET",
isArray: false
},
getWidgetData: {
params: {path: 'widgets'},
method: "GET",
isArray: false
}
})
}])
.controller('WidgetsController',
['$scope', 'Widgets', function ($scope, Widgets) {
$scope.widget = Widgets.getWidget({
id: 1,
foo: 'bar'
});
}]);
That would a make GET request to /api/widgets/1?foo=bar
. You can include a nested object or an array like this and it will be serialised and appended to the url
// In controller
.controller('WidgetsController',
['$scope', 'Widgets', function ($scope, Widgets) {
$scope.widget = Widgets.getWidget({
id: 1,
fields: ['name', 'price']
});
}]);
This would make a GET request to /api/widgets/1?fields=name&fields=price
. I usually prefer to use the $httpParamSerializerJQLike
serializer to serialize the parameters in this form /api/widgets/1?fields[]=name&fields[]=price
which in my experience is less problematic. To use this serializer, you need to configure $http
like so
angular
.module('myMod')
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.paramSerializer = '$httpParamSerializerJQLike';
}])
Hope that helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.