I can't call service from controller - angularjs

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

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?

using ngResource factory in controller showing error

hi everyone I am new with angular js I want to get data through getting method using Resource I have to build a resource factory but when I call this factory in controller I got this error Error: Users.myUser is undefined Please anyone can tell what I have done wrong or why I am getting this error here is my code.
var Myapp = angular.module('starter.controllers', ['ngResource'])
.config(['$resourceProvider', function ($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
}]);
Myapp.factory('Users', function ($resource) {
return{
myUser:
$resource('some url', {}, {
query: {
method: 'POST',
params: {},
isArray: false
}
})
};
});
Myapp.controller('DashCtrl', function ($scope,Users) {
Users.myUser.query().$promise.then(function (data) {
console.log(JSON.stringify(data, null, 4));
}, function (error) {
console.log('Error is: ' + JSON.stringify(error, null, 4));
});
});
You should return $resource object from myUser factory function.
Myapp.factory('Users', function($resource) {
return {
myUser: function() {
return $resource('some url', {}, {
query: {
method: 'POST',
params: {},
isArray: false
}
});
}
}
});
Controller
Myapp.controller('DashCtrl', function ($scope,Users) {
//Call myUser method like below
Users.myUser().query().$promise.then(function (data) {
console.log(JSON.stringify(data, null, 4));
}, function (error) {
console.log('Error is: ' + JSON.stringify(error, null, 4));
});
});
Update your factory as below
Myapp.factory('Users', function ($resource) {
function myUser() {
return $resource('some url', {}, {
query: {
method: 'POST',
params: {},
isArray: false
}
})
}
});

angular.js:13424 TypeError: $scope.entry.update is not a function. Updating the correct way with angularjs

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.

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

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