I have just started using $resource to retrieve data and I'm having problems implementing a custom action. The standard GET is using an object ID as follows;
pageContentService.get({ pageId: 1 }, function (data) {
vm.pageContent = data.content;
});
I also want to be able to retrieve the same data using a string as follows;
pageContentService.getByPageName({ pageName: "Home" }, function (data) {
vm.pageContent = data.content;
});
My $resource service is;
(function () {
"use strict";
angular
.module("common.services")
.factory("pageContentService", ["$resource", pageContentService]);
function pageContentService($resource) {
return $resource("/api/pageContent/:pageId", null,
{
"getByPageName": { method: "GET", url: "/api/pageContent/:pageName", isArray: false }
});
};
})();
And I have mocked the backend as follows;
(function (undefined) {
"use strict";
var app = angular.module("pageContentServiceMock", ["ngMockE2E"]);
app.run(function ($httpBackend) {
var content = [
{ "pageId": 0, "pageName": "Unknown", "content": "<h1>Page not found</h1>" },
{ "pageId": 1, "pageName": "Home", "content": '<h1>Home Page</h1>' },
{ "pageId": 2, "pageName": "Programs", "content": '<h1>Programs Page</h1>' }
];
var contentUrl = "/api/pageContent";
$httpBackend.whenGET(contentUrl).respond(content);
var contentById = new RegExp(contentUrl + "/[0-9][0-9]*", '');
$httpBackend.whenGET(contentById).respond(function (method, url, data) {
var pageContent = content[0];
var parameters = url.split("/");
var length = parameters.length;
var pageId = parameters[length - 1];
if (pageId > 0) {
for (var i = 0; i < content.length; i++) {
if (content[i].pageId == pageId) {
pageContent = content[i];
break;
}
}
}
return [200, pageContent, {}];
});
var contentByName = new RegExp(contentUrl + "/[a-z][A-Z]*", '');
$httpBackend.whenGET(contentByName).respond(function (method, url, data) {
var pageContent = content[0];
var parameters = url.split("/");
var length = parameters.length;
var pageName = parameters[length - 1];
if (pageName.length > 0) {
for (var i = 0; i < content.length; i++) {
if (content[i].pageName == pageName) {
pageContent = content[i];
break;
}
}
}
return [200, pageContent, {}];
});
});
})();
The code works as expected when using the "pageId" to return the data however it doesn't appear to execute the "getByPageName" action of the service in the latter code.
From my understanding the custom action is used to extend the existing functionality of the standard $resource methods so I presume I am not implementing it correctly.
You can try with something like this:
angular.module('common.services').factory('pageContentService', ['$resource',
function($resource) {
return {
getByPageName: $resource('/api/pageContent/:pageName', {pageName: '#pageName'}, { method: "GET", isArray: false }),
getByPageId: $resource('/api/pageContent/:id', {id: '#id'}, { method: "GET", isArray: false })
};
}
]);
And after injecting pageContentService in a controller you can retrieve your data by:
pageContentService.getByPageName({ pageName: "Home" }, function (data) {
vm.pageContent = data.content;
});
Or:
pageContentService.getByPageId({ id: 1 }, function (data) {
vm.pageContent = data.content;
});
The problem turned out to be in the mocking. I was using;
var contentByName = new RegExp(contentUrl + "/[a-z][A-Z]*", '');
When I should have been using;
var contentByName = new RegExp(contentUrl + "/[a-zA-Z]+", '');
Once I fixed that I could use either;
pageContentService.get({ pageId: 1 }, function (data) {
vm.pageContent = data.content;
});
To retrieve the data using the default "GET" or;
pageContentService.getByPageName({ pageName: "Home" }, function (data) {
vm.pageContent = data.content;
});
To use the custom action. I also tried Michelem's suggestion using;
function pageContentService($resource) {
return {
"getByPageId": $resource('/api/pageContent/:pageId', null, { method: "GET", isArray: false }),
"getByPageName": $resource('/api/pageContent/:pageName', null, { method: "GET", isArray: false })
};
}
But I couldn't get this to work.
Related
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 a service class in angular that calls my backend and gets a userInfo as an object. My angular service class has the following.
var userResource = $resource(coreURL+'getFullProfile', {}, {
getUserInfo: {
method: 'POST'
}
userService.getUserInfo = function (userObj) {
var res = userResource.getUserInfo();
var promises = res.$promise;
return promises;
}
My controller class has the following.
promise = userService.getUserInfo();
promise.then(function (response) {
$scope.user = response;
});
My backends service returns an object.
My problem is I get the user info Object from backend but its not properly wrapped inside a object.the object is mix up with some angular variables. I dont have a response.data .the response object itself has all the information.
$promise: Objectcatch: function (callback) {finally: function (callback) {then: function (callback, errback, progressback) {__proto__:
Object
$resolved: true
about: "sdadsf"
country: "India"
creationDate: "2015-04-07"
email: "user3"
id: 3
industries: Array[2]
name: "user3"
phoneNo: 0
progressLevel: 1
The above response contains $promise and $resolved combined in my object. how can I get my data separately as an object.
controller.js
(function () {
var userController;
userController = function ($scope, userService, searchService) {
var delegate;
var masterUser;
$scope.user = {};
$scope.newEducation = [];
$scope.newProfession = [];
$scope.editMode=false;
$scope.hospitals=[];
$scope.yearOptions={
'year-format': "'yy'",
'starting-day': 1,
'datepicker-mode':"'year'",
'min-mode':"year"
};
$scope.hospit=function(){
promise = userService.getHospitals();
promise.then(function (response) {
$scope.hospitals = response.data;
});
};
delegate = {
getUserInfo: function () {
userService.getUserInfo(this.onGetUserData,this.onGetError);
},
onGetUserData :function(data){
var usr = (new dcuser(data));
$scope.user = usr;
$scope.masterUser = angular.copy(usr);
},
onGetError :function(data){
alert("error");
},
saveUserInfo:function(){
alert('saveUserInfo');
userService.saveUserInfo($scope.user,this.onSaved);
},
onSaved:function(){
$scope.editMode=false;
},
enableEdit:function(){
$scope.editMode = true;
},
cancelEdit:function(){
angular.copy($scope.masterUser, $scope.user);
$scope.editMode = false;
delegate.getUserInfo();
},
getIndustries :function(){
alert("getIndustries");
},
searchHospitals :function(){
searchService.searchHospitals("a",this.onGetHospitals);
},
onGetHospitals :function(data){
$scope.hospitals = data;
},
searchMedicalSchools :function(){
searchService.searchMedicalSchools("a",this.onGetMedicalSchools);
},
onGetMedicalSchools :function(data){
$scope.medicalSchools = data;
},
connectUser:function(user){
alert("connectUser");
userService.connectUser(user,this.onConnectSuccess,this.onGetError);
},
onConnectSuccess:function(){
alert("connection request sent");
},
initProfieCompletion: function(){
alert("in");
$scope.user.profession = [];
$scope.user.profession.push({
"hospital": "as",
"speciality": "as",
"fromDate": "",
"toDate": ""
});
promise = userService.getHospitals();
promise.then(function (response) {
$scope.hospitals = response.data;
});
},
addEducation:function(){
$scope.newEducation.push({
"medicalSchool": "",
"speciality": "",
"degree": "",
"graduatedYear": ""
});
},
addProfession:function(){
$scope.newProfession.push({
"hospital": "",
"speciality": "",
"fromDate": "",
"toDate": ""
});
}
};
return $scope.delegate = delegate;
}
dc.userModule.controller('userController', userController);
}).call(this);
service.js
(function () {
"use strict";
dc.app.service('userService', ['$rootScope','$resource', '$http', function ($rootScope,$resource, $http) {
var userService = {};
var coreURL = $rootScope.coreURI+'user/';
var userResource = $resource(coreURL+'getFullProfile', {}, {
getUserInfo: {
method: 'GET'
},
saveUserInfo: {
method: 'POST',
url: coreURL+'updateUserInfo'
}
});
var connectResource = $resource(coreURL + 'connectRequest',{}, {
connectUser: {
method: 'POST'
}
});
var userPhotoResource = $resource(coreURL + 'uploadPhoto', {}, {
uploadPhoto: {
method: 'POST'
}
});
userService.getUserInfo = function (onSuccess,onFailure) {
return(userResource.getUserInfo(onSuccess,onFailure));
},
userService.saveUserInfo = function(user,onSuccess){
return userResource.saveUserInfo(user,onSuccess);
},
userService.connectUser = function(user,onSuccess,onFailure){
return connectResource.connectUser(user,onSuccess,onFailure);
},
userService.uploadPhoto =function(image){
var promises = userPhotoResource.uploadPhoto(image);
return promises;
},
userService.getHospitals = function(){
alert('ser');
var promises = $http.get('dcResources/hospitals.json');
return promises;
}
return userService;
}]);
}).call(this);
I have this code in my post.serv.js and in my controller I want to execute the function delete.
"use strict";
app.factory('JnttPost', function ($resource) {
var PostResource = $resource('/api/post/:_id', {
_id: "#id"
}, {
update: {
method: 'PUT',
isArray: false
}
}, {
delete: {
method: 'DELETE',
isArray: false
}
});
return PostResource;
});
I already know how to get and update a post, for example in my createpost.serv.js
"use stric";
app.factory('JnttCreatePost', function ($http, $q, JnttPost) {
return {
createPost: function (newPostData) {
var newPost = new JnttPost(newPostData);
var dfd = $q.defer();
newPost.$save().then(function () {
dfd.resolve();
}, function (response) {
dfd.reject(response.data.reason);
});
return dfd.promise;
}
};
});
and in my newpost.ctrl.js
"use strict";
app.controller('CtrlNewPost',
function ($scope, $location, JnttIdentity, JnttNotifier, JnttCreatePost) {
var email = ...;
$scope.newPost = function () {
var newPostData = {...};
JnttCreatePost.createPost(newPostData).then(function () {
JnttNotifier.notify('success', 'The post has been created');
$location.path('/');
}, function (reason) {
JnttNotifier.notify('error', reason);
});
};
});
I can't realize how to perform the delete request, I can do with a $http
In my new controller for do deletePost() function I have this:
$scope.deletePost = function () {
var pwd = JnttIdentity.currentUser.hashed_pwd;
var postidd = {
password: pwd,
id: $scope.post._id
};
var config = {
method: "DELETE",
url: '/api/post/',
data: postidd,
headers: {
"Content-Type": "application/json;charset=utf-8"
}
};
$http(config);
$location.path('/');
};
This actually already do this stuff but I want to do this without the $http like the create request, How I can do this? How do I can edit this code below for do the request?
createPost: function (newPostData) {
var newPost = new JnttPost(newPostData);
var dfd = $q.defer();
newPost.$save().then(function () {
dfd.resolve();
}, function (response) {
dfd.reject(response.data.reason);
});
return dfd.promise;
}
In my routes.js in express I have this route:
app.delete('/api/post/', posts.deletePost);
You can either call delete on the $resource class you create (JnttPost) or call $delete on a post that's returned from the $resource class.
The $resource class already has get/save/query/remove/delete functions included so you don't need to add the delete (save is create/POST, so you need to include update with PUT).
Here's a sample of using your $resource class to call delete:
angular.module('test', ['ngResource'])
.factory('JnttPost', function ($resource) {
var PostResource = $resource('/api/post/:_id', {
_id: "#id"
}, {
update: {
method: 'PUT',
isArray: false
}
});
return PostResource;
})
.run(function(JnttPost){
JnttPost.delete({id: 123123123});
});
I have a HTTP based RESTful APIs
When i connect for example to www.domain.com/chiamate/ELSENWZ i got this result:
{
"TICKET": "155112-I",
"TICKET_2": "ATRE6463",
"ACCOUNT_NAME": "PIPPO",
"CUSTOMER_NUMBER": "AG5",
"PROBLEM_TYPE": "H",
"VENDOR": "ITALWARE-CON",
"DESCR": "HP 6300 PRO SFF",
}
I have implemented into AngularJS a service to use the rest api in this way:
var services = angular.module('ngdemo.services', ['ngResource']);
services.factory('ChiamataFactory', function ($resource) {
return $resource('/chiamate/:id', {}, {
show: { method: 'GET',
isArray: false, // <- not returning an array
transformResponse: function(data, headers){
var wrapped = angular.fromJson(data);
alert(JSON.stringify(wrapped, null, 4));
angular.forEach(wrapped.items, function(item, idx) {
wrapped.items[idx] = new Post(item); //<-- replace each item with an instance of the resource object
});
return wrapped;
} },
create: { method: 'POST' },
update: { method: 'PUT', params: {id: '#id'} },
})
});
because i want that when the controller use the service,
$scope.chiamata = ChiamataFactory.show({id: 'ELSENWZ'});
into result i need to add some extra properties.
The problem is that the service don't use the transformResponse
It is not possible to use the transformResponse to decorate the data with data from an asynchronous service
Try this pseudo-code
angular.module('myApp').service('MyService', function($q, $resource) {
var getResult = function() {
var fullResult = $q.defer();
$resource('url').get().$promise.then(function(data) {
var partialPromises = [];
for (var i = 0; i < data.elements.length; i++) {
var ires = $q.defer();
partialPromisses.push(ires);
$resource('url2').get().$promise.then(function(data2) {
//do whatever you want with data
ires.resolve(data2);
});
$q.all(partialPromisses).then(function() {
fullResult.resolve(data);
});
return fullResult.promise; // or just fullResult
}
});
};
return {
getResult: getResult
};
});
or you can use transformResponce with $http as described in the documentation
angular $http documentation
Ok, so I have this service that is dependent on another service value that the user can change in the app interface. Something like this:
app.service('Applications', ['$resource', 'URL',
function ($resource, URL) {
var applicationsResource = $resource(URL + '/applications/:id', { id: '#id' }, {
query: {
method: 'GET',
isArray: true,
transformResponse: function(body, header) {
var response = angular.fromJson(body);
return response.data.applications;
}
}
});
var applications = applicationsResource.query(function() {
applications.current = applications[0];
});
return applications;
}
]);
app.service('Users', ['$resource', 'URL', 'Applications',
function ($resource, URL, Applications) {
return $resource(URL + '/users/:id', { id: '#id' }, {
query: {
method: 'GET',
isArray: true,
headers: {
'User': Applications.current.username,
'Pass': Applications.current.password
},
transformResponse: function(body, header) {
var response = angular.fromJson(body);
return response.data.users;
}
}
});
}
]);
Example of working controller code:
app.controller('usersController', ['$scope', '$resource', 'URL', 'Applications',
function ($scope, $resource, URL, Applications) {
$scope.users = [];
$scope.reload = function() {
$scope.loading = true;
var usersResource = $resource(URL + '/users/:id', { id: '#id' }, {
query: {
method: 'GET',
isArray: true,
headers: {
'User': Applications.current.username,
'Pass': Applications.current.password
},
transformResponse: function(body, header) {
var response = angular.fromJson(body);
return response.data.users;
}
}
});
$scope.users = usersResource.query(function() {
$scope.loading = false;
});
/*
// after injecting Users, this is what I want to do, instead of what's above
$scope.users = Users.query(function() {
$scope.userTable.reload();
$scope.loading = false;
});
*/
};
$scope.$watch('Applications.current', function (newApplication, oldApplication, scope) {
if (newApplication && newApplication !== oldApplication) {
scope.reload();
}
});
}
]);
I want to replace that usersResource with my Users service, but that's where I'm stuck now.
The issue is that no matter what I do, the Applications.current on the Users service is always null. (I only make use of this service after making sure that Applications.current is not null on the controller)
If I move the resource directly to the controller, it works, but I want to move these away from the controllers.
Any tips on how to fix or improve this?
You should know that $resource is async and you call Users service before actually you got response from server and populated applications.current. This a reason why Applications.current is null into Users service.
In your case I would use Uses service into Applications:
app.service('Applications', ['$resource', 'URL', 'Users',
function ($resource, URL, Users) {
var applicationsResource = $resource(URL + '/applications/:id', { id: '#id' }, {
query: {
method: 'GET',
isArray: true,
transformResponse: function(body, header) {
var response = angular.fromJson(body);
return response.data.applications;
}
}
});
var applications = applicationsResource.query(function() {
applications.current = applications[0];
// call the Users
Users.query(applications.current) /**/
return /* ... */;
});
return applications;
}
]);