using ngResource factory in controller showing error - angularjs

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

Related

AngularJS error [$injector:unpr] Unknown provider: in IE11 with Minified JS

I am using angularjs and want cross browser compatbility. It works fine in Chrome and firefox but in IE11 it is giving.
angular
.module('app')
.factory('AgencyFactory', AgencyFactory)
.factory('AdminService', adminService);
adminService.$inject = ['$resource'];
function adminService($resource) {
return {
UpdateLeadStatus:
$resource('/Agency/UpdateLeadStatus/Ids/:Ids/StatusId/:StatusId/ProducerId/:ProducerId', {}, {
change: {
method: 'POST',
params: {},
isArray: false
}
}),
AssignProducer: $resource('/Agency/AssignProducer/AutoAssign/:AutoAssign', {}, {
change: {
method: 'POST',
params: {},
isArray: false
}
}),
UpdateProducerAssignedStatus: $resource('/Agency/UpdateProducerAssignedStatus/Ids/:Ids/Status/:Status/AutoAssign/:AutoAssign', {}, {
change: {
method: 'POST',
params: {},
isArray: false
}
}),
};
}
AgencyFactory.$inject = ['AdminService', '$uibModal', 'modalService', '$rootScope'];
function AgencyFactory(AdminService, $uibModal, modalService, $rootScope) {
function UpdateLeadStatus(Ids, StatusId, ProducerId) {
return AdminService.UpdateLeadStatus.change({
Ids: Ids,
StatusId: StatusId,
ProducerId: ProducerId
}).$promise;
}
function AssignProducer(AutoAssign) {
return AdminService.AssignProducer.change({
AutoAssign: AutoAssign
}).$promise;
}
function UpdateProducerAssignedStatus(Ids, Status, AutoAssign) {
return AdminService.UpdateProducerAssignedStatus.change({
Ids: Ids,
Status: Status,
AutoAssign: AutoAssign
}).$promise;
}
return {
UpdateLeadStatus: UpdateLeadStatus,
AssignProducer: AssignProducer,
UpdateProducerAssignedStatus: UpdateProducerAssignedStatus,
};
}
})();
When I use un-minified code it works fine, but when I minify it, it shows the Error

ngResource ($resource) is returning 404 for PUT

It's been a while since I've used $resource for managing my service calls.
For some reason, all my calls are working ok and reaching my REST end-points, basically /api/profile and /api/profile/:id.
But for some reason, my put returns as 404.
Anyone have an Idea of what may be going on.
Thanks and Cheers!
'use strict';
angular.module('chainLinkApp')
.config(['$stateProvider', function($stateProvider){
$stateProvider
.state('profile', {
url:'/profile/:id',
templateUrl:'views/profile.html',
controller:'ProfileController',
controllerAs:'profile'
});
}])
.controller('ProfileController',['$scope', '$http', 'profileFactory', function($scope, $http, profileFactory){
$scope.updateMode = false;
$scope.comments = profileFactory.getProfiles.go().$promise.then(function(response){
$scope.comments = response;
});
$scope.getProfile = function(commentId){
$scope.comment = profileFactory.getProfile.go({id:commentId}).$promise.then(function(response){
$scope.comment = response;
$scope.updateMode = true;
}, function(error){
return console.log('An error has occured', error);
});
};
$scope.addProfile = function(comment){
profileFactory.postProfile.go(comment).$promise.then(function(){
console.log('Your post was a success');
$scope.comment = {};
}, function(error){
console.log('There was an error: ', error);
});
};
$scope.updateProfile = function(comment){
profileFactory.updateProfile.go(comment._id, comment).$promise.then(function(response){
console.log('Your profile has been updated');
$scope.updateMode = false;
$scope.comment = {};
}, function(error){
console.log('There is an error: ', error);
});
};
}])
.factory('profileFactory', ['$resource', function($resource){
return{
getProfiles: $resource('/api/profile', {}, { go: { method:'GET', isArray: true }}),
getProfile: $resource('/api/profile/:id',{},{ go: { method: 'GET', params: { id: '#id' }}}),
postProfile: $resource('/api/profile', {}, { go: { method: 'POST' }}),
updateProfile: $resource('/api/profile/:id', {}, { go: { method: 'PUT', params: { id:'#id' }}})
};
}]);
The way of you are using $resource is strange, it should be like this:
.factory('UserService', function($resource) {
return $resource('/api/users/:id', {}, {
'create': { method: 'POST' },
'update': { method: 'PUT', params: { id: '#id'} }
});
})
Then you call the service like this: UserService.create(theUserobj, function(result) { ... })

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.

DELETE Restful method with angularjs $resource

I'm attemping to call a RESTful method via $resource as following:
Resource:
angular.module('secure',['ngResource']).factory('Vehicle', function ($resource) {
return $resource('/secure/vehicle/index', { id: '#id' }, {
query: {
method: 'GET',
isArray: true
},
delete: {
method: 'DELETE',
isArray: false,
url: '/secure/vehicle/delete/:id'
}
});
});
Then, from other service I inject the above factory and I call DELETE method in this way:
factory.delete = function (procedureId) {
var vehicle = new Vehicle();
vehicle.$delete({id: procedureId}, function () {
//success
deferred.resolve();
}, function (errResponse) {
// fail
console.log(errResponse);
});
return deferred.promise;
};
(Don't pay attention to deferred things, it doesn't work with or without it)
Unfortunately, I always get the same answer:
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/secure/vehicle/delete/21
Request Method:DELETE
Status Code:422 Unprocessable Entity
The call itself is set up properly (secure/vehicle/delete/21). In fact, if I do the same, but instead of using $resource variable, using $http, everything works!
$http({
'method': 'DELETE',
'url': '/secure/vehicle/delete/' + procedureId,
'headers': {
'Content-Type': 'application/json'
},
'data': ""
})
.success(function () {
// success
})
.error(function (data, status) {
console.log(data.errors);
});
So, I guess something is missing in $resource-way, but what? Any help, it will be appreciated!
EDIT:
It seems it's a backend problem when it reads the entire url call. If I call DELETE resource, using $http, adding the data: "" as I show above, the backend initializes itself properly.
But if I try the $resource-way, the required params are pre-configured and that doesn't like to the backend, so I need to find the way to say to $resource how to add something like data: "", any ideas?
Test proof that it works:
angular.module('secure', ['ngResource']).factory('Vehicle', function($resource) {
return $resource('/secure/vehicle/index', {
id: '#id'
}, {
query: {
method: 'GET',
isArray: true
},
delete: {
method: 'DELETE',
isArray: false,
url: '/secure/vehicle/delete/:id'
}
});
});
angular.module('secure').factory('VehicleFactory', function(Vehicle, $q) {
var factory = {}
factory.delete = function(procedureId) {
var deferred = $q.defer();
var vehicle = new Vehicle();
vehicle.$delete({
id: procedureId
}, function(r) {
deferred.resolve(r);
}, function(errResponse) {
console.log(errResponse);
});
return deferred.promise;
};
return factory;
});
describe('VehicleFactory', function() {
var $httpBackend, VehicleFactory
beforeEach(module('secure'));
beforeEach(inject(function(_$httpBackend_, _VehicleFactory_) {
$httpBackend = _$httpBackend_
VehicleFactory = _VehicleFactory_
}))
it('deletes vehicle - vehicle.$delete()', function() {
var r = {
data: 'correct response'
}
$httpBackend.when('DELETE', '/secure/vehicle/delete/123').respond(r)
VehicleFactory.delete(123).then(function(response) {
expect(response.data).toBe(r.data)
})
$httpBackend.flush();
});
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation()
$httpBackend.verifyNoOutstandingRequest()
})
})
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-resource.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>
Some much cleaner way to write delete functionality without $q:
angular.module('secure').factory('VehicleFactory', function(Vehicle) {
var factory = {}
factory.delete = function(procedureId) {
return (new Vehicle()).$delete({
id: procedureId
})
}
return factory;
});

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

Resources