Calling Service Functions - angularjs

I have following service with 2 functions. I want to call this from my controller so i did but gives me error :-
angular.module('myApp')
.factory('Practices', function ($resource) {
return {
UpdatePractice: function () {
return $resource('/api/practicesUpdate/:practiceId', {
practiceId: '#_id'
}, { //parameters default
update: {
method: 'PUT'
}
});
},
UpdateCreditCard: function () {
return $resource('/api/practicesCreditCardUpdate/:practiceId', {
practiceId: '#_id'
}, { //parameters default
updateCredit: {
method: 'PUT'
}
});
}
}
});
Calling from controller :-
Practices.UpdatePractice.update($scope.practice);

Practices.UpdatePractice.update($scope.practice);
UpdatePractice is a function and needs to be executed first...
Practices.UpdatePractice().update($scope.practice);

Related

How to instantiate angular service with multiple resources?

I have an angular service based on meanjs for rents. Originally it looked like this:
(function () {
'use strict';
angular
.module('rents.services')
.factory('RentsService', RentsService);
RentsService.$inject = ['$resource', '$log'];
function RentsService($resource, $log) {
var Rent = $resource(
'/api/rents/:rentId',
{
rentId: '#_id'
},
{
update: {
method: 'PUT'
},
getByCarId:
{
method: 'POST',
params: {
rentId: 'bycar'
},
isArray: true,
hasBody: true,
requestType: 'json',
responseType: 'json'
}
}
);
angular.extend(Rent.prototype, {
createOrUpdate: function () {
var rent = this;
return createOrUpdate(rent);
}
});
return Rent;
// and all other function that are the same as down below
}());
Then I added a second resource
(function () {
'use strict';
angular
.module('rents.services')
.factory('RentsService', RentsService);
RentsService.$inject = ['$resource', '$log'];
function RentsService($resource, $log) {
var Rent =
{
basic: $resource(
'/api/rents/:rentId',
{
rentId: '#_id'
},
{
update: {
method: 'PUT'
},
getByCarId:
{
method: 'POST',
params: {
rentId: 'bycar'
},
isArray: true,
hasBody: true,
requestType: 'json',
responseType: 'json'
}
}
),
carUsageStats: $resource(
'/api/rents/car_usage'
)
};
angular.extend(Rent.basic.prototype, {
createOrUpdate: function () {
var rent = this;
return createOrUpdate(rent);
}
});
return Rent;
function createOrUpdate(rent) {
if (rent._id) {
return rent.$update(onSuccess, onError);
} else {
return rent.$save(onSuccess, onError);
}
// Handle successful response
function onSuccess(rent) {
// Any required internal processing from inside the service, goes here.
}
// Handle error response
function onError(errorResponse) {
var error = errorResponse.data;
// Handle error internally
handleError(error);
}
}
function handleError(error) {
// Log error
$log.error(error);
}
}
}());
Until I added second resource, this resolve function for creating new rent worked fine
newRent.$inject = ['RentsService'];
function newRent(RentsService) {
return new RentsService();
}
But when I added second resource (and had to address the one I want by using property name - cant use Rent.query() but Rent.basic.query()) instantiating new Rent no longer works. I added console log outputs around and code stops executing at line var rent = new RentsService(). Querying works fine. What is the correct way of making new object using service with multiple resources?

Multiple functions in service not allowing for module creation

I have a CRUD module activities instead of the default articles but the structure of the module is the same.
When I select to go to the page where I create a new activity, activities.create state is invoked (like the articles one)
.state('activities.create', {
url: '/create',
templateUrl: 'modules/activities/client/views/form-activity.client.view.html',
controller: 'ActivitiesController',
controllerAs: 'vm',
resolve: {
activityResolve: newActivity
},
data: {
roles: ['user', 'admin'],
pageTitle: 'Activities Create'
}
})
function newActivity(ActivitiesService) {
return new ActivitiesService().getActivitiesOfAllUsers();
}
And my ActivitiesService looks like this:
function ActivitiesService($resource, Authentication) {
return {
getActivitiesOfCurrentUser: function() {
return $resource('api/:userId/activities/:activityId', {
userId: Authentication.user._id,
activityId: '#_id'
}, {
update: {
method: 'PUT'
}
});
},
getActivitiesOfAllUsers: function() {
return $resource('api/activities/:activityId', {
activityId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
}
}
The default setup the ActivitiesService was:
function ActivitiesService($resource, Authentication) {
return $resource('api/:userId/activities/:activityId', {
userId: Authentication.user._id,
activityId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
And the newActivity function would look like this:
function newActivity(ActivitiesService) {
return new ActivitiesService();
}
So when the service is in the default layout, going to the create page works just fine.
However, adding another function to the service as I have done is breaking it. When I select to go to the create page, there are no errors and no indications anywhere as to why nothing is happening.
From what I can see, the activityResolve should evaluate the same and I cannot figure out why it's not working.
Based on the accepted answer here, I found the answer. I amended the ActivitiesService to this:
function ActivitiesService($resource, Authentication) {
return {
getActivitiesOfCurrentUser: $resource('api/:userId/activities/:activityId', {
userId: Authentication.user._id,
activityId: '#_id'
}, {
update: {
method: 'PUT'
}
}),
getActivitiesOfAllUsers: $resource('api/activities/:activityId', {
activityId: '#_id'
}, {
update: {
method: 'PUT'
}
})
};
}
And changed the newActivity function to:
function newActivity(ActivitiesService) {
return new ActivitiesService.getActivitiesOfAllUsers;
}
(so without the parentheses on ActivitiesService)

Factory that serves multiple resource in angular

I intend to return few resource from a factory, but unfortunately it failed in my case. It shows the error message Entry is not a function Scope.$scope.create.
This is working code with one resource:
angular.module('Entry').factory('Entry', function($resource) {
return $resource('/api/entries/:id', { id: '#_id' }, {
update: {
method: 'PUT'
}
});
});
$scope.create = function() {
var entry = new Entry({
});
entry.$save(function() {});
}
This is not working code after adding multiple resource:
angular.module('Entry').factory('Entry', function($resource) {
return {
'EntryA': $resource('/api/entries/:id', { id: '#_id' }, {
update: {
method: 'PUT'
}
}),
'EntryB': $resource('/api/entries/:id', { id: '#_id' }, {
update: {
method: 'PUT'
}
}),
};
});
$scope.create = function() {
var entry = new Entry({
});
entry.EntryA.$save(function() {});
}

I can't call service from controller

I'm trying to call service from my controller
leadService.loadPage.query({pageNumber: pageNumber}, success, error);
Service definition
define([], function() {
return ['$resource', function ($resource) {
return {
loadPage: loadPage
};
function loadPage() {
return $resource('http://localhost/api/loadPage/:pageNumber', null, {
query: {
method: 'GET',
params: {
pageNumber: '1'
},
isArray: true
}
});
}
}]
})
It shows error TypeError: undefined is not a function. It probably can't fire query statement.
I'm using RequireJS with AngularJS.
You have two problems here. The first one was spotted by #MannyD. You must fix the function definition like this (i.e. declaring the function before the return statement which references it):
define([], function() {
return ['$resource', function ($resource) {
function loadPage() {
return $resource('http://localhost/api/loadPage/:pageNumber', null, {
query: {
method: 'GET',
params: {
pageNumber: '1'
},
isArray: true
}
});
}
return {
loadPage: loadPage
};
}]
})
The second problem is the one I spotted: a call like leadService.loadPage.query({pageNumber: pageNumber}, success, error); will trigger an error because loadPage is a function and not a $reource. You must either add the parens in the definition OR add the parent in the call. This means:
define([], function() {
return ['$resource', function ($resource) {
function loadPage() {
return $resource('http://localhost/api/loadPage/:pageNumber', null, {
query: {
method: 'GET',
params: {
pageNumber: '1'
},
isArray: true
}
});
}
return {
loadPage: loadPage()
};
}]
});
//...
leadService.loadPage.query({pageNumber: pageNumber}, success, error);
OR
define([], function() {
return ['$resource', function ($resource) {
function loadPage() {
return $resource('http://localhost/api/loadPage/:pageNumber', null, {
query: {
method: 'GET',
params: {
pageNumber: '1'
},
isArray: true
}
});
}
return {
loadPage: loadPage
};
}]
});
//...
leadService.loadPage().query({pageNumber: pageNumber}, success, error);

2 Services merge in 1

I have following in my .js file. I am new to angular. Now instead of writing this separately, I want it to be in one service say Practices.
How to do this?
angular.module('myApp').factory('Practices', ['$resource', function ($resource) {
return $resource('/api/practices/:statusController/:statusId/:searchController/:searchId/:practiceId/:pageController/:pagenum', {
practiceId: '#practiceId',
statusId: '#statusId',
statusController: '#statusController',
searchId: '#searchId',
searchController: '#searchController',
pagenum: '#pagenum',
pageController: '#pageController'
});
}]);
angular.module('myApp')
.factory('PracticesEdit', function ($resource) {
return {
UpdatePractice: function () {
return $resource('/api/practicesUpdate/:practiceId', {
practiceId: '#_id'
}, { //parameters default
update: {
method: 'PUT'
}
});
},
UpdateCreditCard: function () {
return $resource('/api/practicesCreditCardUpdate/:practiceId', {
practiceId: '#_id'
}, { //parameters default
updateCredit: {
method: 'PUT'
}
});
}
}
});
angular.module('myApp').factory('PracticesService', function ($resource) {
var practices = $resource(...);
return {
updatePractice: function () {
// the same
},
updateCreditCard: function () {
// the same
},
practices: practices
}
});
and then you can use it in controller as
PracticesService.practices;
PracticesService.updateCreditCard();
PracticesService.updatePractice();

Resources