Multiple functions in service not allowing for module creation - angularjs

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)

Related

Refactoring angular resource chaining

Basically i have a angular resource API service as follow. I have use the nested chaining method as below which i think is not so good in coding perspective (especially when there are multiple chaining needed)
angular.module('user')
.factory('UserAPI', ['$resource'],
function ($resource) {
return $resource('User', {},
{
GetUserDetail1: {
method: 'GET',
url: url1
},
GetUserDetail2: {
method: 'GET',
url: url2
}
}
}
)
UserAPI.GetUserDetail1({ ID: id }).$promise.then(function (res) {
UserAPI.GetUserDetail2({ ID: res.userID }).$promise.then(function (res1) {
}, function (errRes1) {
});
}, function (errRes) {
});
So, I am now thinking of refactoring the code as follow but I am not sure whether this could be done.
function getUserDetail2 (res) {
};
UserAPI.GetUserDetails1({ ID: id})
.then(getUserDetail2(res))
.catch(function (errRes) {
// catch error if any error occur
});
You just need to pass reference of function instead of calling it there.
UserAPI.GetUserDetails1({ ID: id})
.then(getUserDetail2) //passed getUserDetail2 method here
.catch(function (errRes) {
// catch error if any error occur
});

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);

"Suggest slug name" API call in ngResource in AngularJS/Express app

I want the user to be able to set the slug name (URL) for a document in my app, but also I need some control so users don't override each other. It needs to be a separate call (not integrated with create/update) so the user can get visual feedback on their own slug name suggestions.
Therefore I've created a suggestSlug API call that takes an optional slug parameter as seed for the final slug name.
This is what my Express routes looks like:
app.get('/api/projects/suggestSlug/:slug', projects.suggestSlug);
app.get('/api/projects/suggestSlug', projects.suggestSlug);
app.get('/api/projects', projects.list);
app.get('/api/projects/:id', projects.show);
Now, I want to extend ngResource on the client side (AngularJS) to make use of this API:
angular.module('myapp.common').factory("projectModel", function ($resource) {
return $resource(
"/api/projects/:id",
{ id: "#id" },
{
update: { method: "PUT", params: { id: '#_id' } },
del: { method: "DELETE", params: { id: '#_id' } }
}
);
});
How do I extend the ngResource client to use my new API?
This was my solution: adding a separate $http-based method to my projectModel:
angular.module('myapp.common').factory("projectModel", function ($resource, $http) {
var projectModel = $resource(
"/api/projects/:id",
{ id: "#id" },
{
update: { method: "PUT", params: { id: '#_id' } },
del: { method: "DELETE", params: { id: '#_id' } }
}
);
projectModel.suggestSlug = function (slugSuggestion, callback) {
$http.get(
'/api/projects/suggestSlug/' + slugSuggestion
).success(callback).error(function(error) {
console.log('suggestSlug error:', error);
});
};
return projectModel;
});

Calling Service Functions

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);

Resources