I'm trying to pass parameter to WebAPI, but something doesn't work. Not sure if I should add :id to the $resource path or not?
My service:
dataService.factory('Widgets', ['$resource', function ($resource) {
var data = $resource('/api/:path', {
path: '#path'
}, {
getWidgets: {
params: { path: 'widgets' },
method: "GET",
isArray: true
},
getWidget: {
params: { path: 'widgets' },
method: "GET",
isArray: true
},
getCategories: {
params: { path: 'widgetCategories' },
method: "GET",
isArray: true
},
});
return data;
}]);
In the controller:
Widgets.getWidget({ id: $rootScope.widgetId }).$promise.then(function (result) {
$scope.widget = result;
});
In ASP.Net Controller:
[HttpGet]
public IEnumerable<Widget> Get()
{
return _dbContext.Widgets;
}
[Route("api/[controller]/{id}")]
[HttpGet]
public Widget Get(int id)
{
return _dbContext.Widgets.Where(w => w.Id == id).FirstOrDefault(); ;
}
Could someone have a look please?
Related
I am new to AngularJS and I have a question here.
I am using $resource for my CRUD actions.
I currently have the code like this,
angular.module("dopAngular.services")
.factory("UserRoleService", ["$resource",
function ($resource) {
return $resource("api/UserRoleApi", {}, {
query: { method: "GET", isArray: true },
create: { method: "POST" },
get: { method: "GET" },
remove: { method: "DELETE" },
update: { method: "PUT" }
});
}]);
//below is the code in my controller
UserRoleService.query(function (data) {
vm.UserRoleLookups = data;
});
I would like to make my UserRoleService generic, which means I don't want to provide the specific URL for the API in the factory level.
I now modify my code a little bit,
angular.module("dopAngular.services")
.factory("UserRoleService", ["$resource",
function ($resource, url) {
return $resource(url, {}, {
query: { method: "GET", isArray: true },
create: { method: "POST" },
get: { method: "GET" },
remove: { method: "DELETE" },
update: { method: "PUT" }
});
}]);
My question is what I should do in my controller?
So, instead of directly returning $resource, we can encapsulate it with a function that accepts url as a param.
Something like this:
myApp.factory('UserRoleService', function($resource) {
return {
query: function(url) {
return $resource(url, {}, {
query: {
method: "GET",
isArray: true
},
get: {
method: "GET"
}
});
}
}
});
Now, in controller, you can call it like:
UserRoleService.query('//httpbin.org').get()
example fiddle
How can I make query from function VisitService to get date method "from" "to" and show in my html page.
Is this code will work good ??
Is better with explainition
(function() {
'use strict';
angular
.module('projectsEvaluationApp')
.factory('EvaluationsService', EvaluationsService)
.factory('VisitService', VisitService)
.factory('WebPagesService', WebPagesService);
EvaluationsService.$inject = ['$resource'];
VisitService.$inject = ['$resource'];
WebPagesService.$inject = ['$resource'];
function EvaluationsService ($resource) {
var service = $resource('api/evaluations/:id', {}, {
'get': {
method: 'GET',
isArray: true
},
'query': {
method: 'GET',
isArray: true,
}
});
return service;
}
function VisitService ($resource) {
var service = $resource('api/visits/:id', {}, {
'get': {
method: 'GET',
isArray: true
},
'query': {
method: 'GET',
isArray: true,
}
});
return service;
}
function WebPagesService ($resource) {
var service = $resource('api/web-pages/:id', {}, {
'get': {
method: 'GET',
isArray: true
},
'query': {
method: 'GET',
isArray: true,
}
});
return service;
}
})();
Thank you
First of to use $resource you need to install and inject ng-resource
You can use like this
function VisitService ($resource) {
return $resource('api/visits/:id', {}, {
}).query();
}
Default query method is GET with default isArray as true
If you want to pass a query parameter
Your API will be
function VisitService (fromDate,toDate) {
return $resource(''api/visits?fromDater' + fromDate + '&toDate' + toDate', {}, {
}).query();
}
Call it in controller
$scope.test = VisitService('01/04/2016','01/04/2016');
User in HTML
{{test}}
I am trying to make an update to an existing object but get the following error $scope.entry.update is not a function.
I created a service called 'budgetResource'
"use strict";
angular.module("common.services").factory("budgetResource", ["$resource", "appSettings", budgetResource])
function budgetResource($resource, appSettings) {
return $resource(appSettings.serverPath + "api/budget/:id", null,
{
'update': { method: 'PUT', isArray: true },
'delete': { method: 'DELETE', isArray: true },
'save': { method: 'POST', isArray: true }
});
}
Herewith the function in my controller where budgetResource service is injected with the function $scope.updateBudgetAmount being called.
$scope.updateBudgetAmount = function (categoryId) {
$scope.entry = new budgetResource();
$scope.entry = {
"budgetAmount": $scope.budgetAmount,
"categoryId": categoryId
}
$scope.entry.update({ id: categoryId },
function (data) {
$scope.categories = data;
$scope.category = "";
},
function (error) {
$scope.message = error.statusText;
});
}
which in turn calls the webapi method
public IHttpActionResult Put(int id, [FromBody]Category cat)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
BudgetRepository repo = new BudgetRepository();
var categories = repo.SaveCategory(cat);
return Ok(categories);
}
How can modify this so that it is dine correctly?
After you do $scope.entry = {...},$scope.entry becomes a plain javascript object, so $scope.entry.update is not exist.
I have multiple factories in my angular service located in different js file. And there is common base of all the queries:
1) Authorization: Bearer token (header) (required after login)
2) AccessDateTime, UserIPAddress (required before login)
3) AccessDateTime, UserIPAddress, UserID (required after login)
Now, I find that it is very tedious to repeat this on each of the resource. How could i make a base for this? I thought that this is something very common but i could not found any documentation on this. Something like jquery.AjaxSetup().
Default Code
angular.module('app.test').factory('Test', ['$resource',
function($resource) {
return {
resource1: $resource(
url: 'test1/:testId/:AccessDateTime/:UserIPAddress',
headers: { Authorization: Bearer token},
params: { testId: '#_id', AccessDateTime:'#AccessDateTime', UserIPAddress: '#UserIPAddress' }
}),
resource2: return $resource(
url: 'test2/:testId/:AccessDateTime',
params: { testId: '#_id', AccessDateTime:'#AccessDateTime' }
});
}
}
]);
Code after base resource implemented(Illustration only)
angular.module('app.base').factory('FactoryBase'), ['resource',
function($resource) {}
if (resource need authorization) {
auto append header, AccessDateTime, UserIPAddress
} else if (resource do not need authorization) {
auto append AccessDateTime
}
// depending on attribute set with authorize: true/false
}
]);
angular.module('app.test').factory('Test', ['$resource',
function($resource) {
require('FactoryBase'),
return {
resource1: $resource(
url: 'test1/:testId',
authorize: true
}),
resource2: $resource(
url: 'test2/:testId',
authorize: false
}),
}
]);
Put modifier functions in your factory:
angular.module('app.test').factory('Test', ['$resource',
function($resource) {
var defaultConfig1 = {
url: 'test1/:testId/:AccessDateTime/:UserIPAddress',
headers: { Authorization: Bearer token},
params: { testId: '#_id',
AccessDateTime:'#AccessDateTime',
UserIPAddress: '#UserIPAddress'
}
};
var defaultConfig2 = {
url: 'test2/:testId/:AccessDateTime',
params: { testId: '#_id',
AccessDateTime:'#AccessDateTime'
}
};
function mod1(arg) {
var obj = defaultConfig1;
//modify config
return obj;
};
function mod2(arg) {
//modify and return defaultConfig
};
return {
resource1: $resource(defaultConfig1),
resource2: $resource(defaultConfig2).
modified1: function (arg) {
return $resource(mod1(arg));
},
modified2: function (arg) {
return $resource(mod2(arg));
}
}
}
]);
You have the full power of JavaScript to modify the configuration objects as you please before returning them.
I'm using angularjs with symfony2. I can't use the same path with a different method.
Angularjs service
angular.module('adminApp')
.service('users', ['$resource', function events($resource) {
function
return $resource(Routing.generate('users'), { id: "#_id" }, {
'create': { method: 'POST' },
'get': { method: 'GET', isArray: false },
'query': { method: 'GET', isArray: true },
'update': { method: 'PUT' },
'delete': { method: 'DELETE'}
});
}]);
Symfony2 Routing
users:
pattern: /users
defaults: { _controller: AppAdminBundle:User:list }
methods: [GET]
options:
expose: true
users:
pattern: /users
defaults: { _controller: AppAdminBundle:User:update }
methods: [PUT]
options:
expose: true
User controller
public function listAction()
{
//list
}
public function updateAction()
{
//update
}
You have two routes named equally.
Name first as users_list, second - users_update and it should work fine.