I'm following the Angular main page and I've extended $resource to add the update method like this:
angular.module('user', ['ngResource']).
factory('User', function($resource) {
var User= $resource('/user/:id', {
update: {
method: 'PUT'
}
});
User.prototype.update = function(cb) {
return User.update({ // this line throws the error
id: this.id
}, angular.extend({}, this, {
_id: undefined
}), cb);
};
However running:
$scope.user.update()
throws a TypeError: Object function h(a){v(a||{},this)} has no method 'update'
I can't see what I'm missing right now, any help appreciated
I found the issue in fact I need to pass an empty object for the paramDefaults arg:
var User= $resource('/user/:id', {}, {
update: {
method: 'PUT'
}
}
You are using the minified angularjs version, so you have to use to array notation. Just inject the required services in an array followed by the function:
angular.module('user', ['ngResource']).
factory('User', ['$resource', function($resource) {
var User= $resource('/user/:id', {
update: {
method: 'PUT'
}
});
User.prototype.update = function(cb) {
return User.update({
id: this.id
}, angular.extend({}, this, {
_id: undefined
}), cb);
});
}]);
Note: the same applies for your directives, controllers, ...
In resource instances, the method name is prefixed with $.
$scope.user.$update({}, cb);
Related
I'm using angularjs 1.5.8.
I get this error when I'm trying to cancel an http request with angular :
$cancelRequest is not a function
My code :
app.factory('User', function($resource) {
var getUsersResource = $resource(
'/users',
null,
{get : {method: 'GET', isArray: true, cancellable: true}}
);
return {
getUsers : function() {
return getUsersResource.get({},
function(data) {
...
}, function(error) {
...
}
);
}
};
});
app.controller('InitController', function($rootScope, User, ...) {
...
User.getUsers();
...
}
app.factory('AuthInterceptor', function($q, $location, $injector) {
return {
responseError: function(response) {
if (response.status === 401) {
$injector.get('$http').pendingRequests.forEach(
function (pendingReq) {
pendingReq.$cancelRequest();
}
);
$location.path('login');
}
return $q.reject(response);
}
};
});
Do you know how I can solve this error ?
Thanks
The documentation suggests that $cancelRequest should be used with the resource object. From my initial review, it appears that you're correctly using $resource within the User factory. But, I'm not sure about how you're implementing this within the AuthInterceptor factory. It doesn't look like you're using User.getUsersSources() at all. Therefore, I believe the reason that you're getting that error is because you're not using $cancelRequestion correctly. That being said, you might have forgotten to include other parts of the code.
Ideally, the resolved $resource object from User.getUserResources() should be passed into AuthInteceptor.
I think that you should declare your service like that:
.factory('categoryService', ['$resource', function($resource) {
return $resource('/', {},
{
'get': {
'method': 'GET',
'cancellable': true,
'url': '/service/categories/get_by_store.json',
},
});
}])
And when you use this service, it should be called so:
if ( $scope.requestCategories ) {
$scope.requestCategories.$cancelRequest();
}
$scope.requestCategories = categoryService['get']({
}, function(res){
//some here
}, function(err){
//some here
});
I have a generic restful resource with angular's $resource. On any save method, I also want to set a message and boolean on whatever scope I'm in, and set a timeout for that message. So anywhere in my code where I call .save/.$save, I then attach a .finally onto it (below).
Rather than putting the same .finally onto every save I call, I'm wondering if I can just write a finally onto the actual resource itself, and have this be a generic finally for my save function.
var resource = $resource(
pageListPath,
{},
{
query: {method:'GET', isArray:true},
get: {method:'GET', url: pageDetailPath, params:{id:'#id'}, cache:true},
save: {method:'PUT', url: pageSavePath, params:{id:'#id'}},
delete: {method:'DELETE', url: pageDetailPath, params:{id:'#id'}}
}
);
return resource;
.finally(function() {
$scope.loading = false;
$timeout(function() {
$scope.message = false;
}, 2500);
});
Ideally something like
save: {
method:'PUT',
url:pageSavePath,
params:{id:'#id'},
finally:function() { doStuff() }}
is what I'm looking for. Is this possible?
I ended up writing another service to encapsulate this one, providing generic functionality for certain responses.
The API service:
pageServices.factory('PageAPI',
['$resource',
function($resource,
var resource = $resource(
pageListPath,
{},
{
query: {
method:'GET',
isArray:true
},
get: {
method:'GET',
url: pageDetailPath,
params:{ id:'#id' }
},
...,
...,
}
);
return resource;
}]
);
pageServices.factory('Page', ['PageAPI',
function(PageAPI) {
var service = {
'getPages': function() {
return PageAPI.query(function(response) {
// Do stuff with success
}, function(err) {
// Handle error
}).$promise.finally(function() {
// Generic finally handler
}
},
...,
...,
}
return service
}
])
how to make Generic method for rest call in angularjs ?
i have tried for single request, it's working fine
UIAppRoute.controller('test', ['$scope', 'checkStatus', function($scope, checkStatus) {
$scope.data = {};
checkStatus.query(function(response) {
$scope.data.resp = response;
});
}])
UIAppResource.factory('checkStatus', function($resource){
return $resource(baseURL + 'status', {}, {'query': {method: 'GET', isArray: false}})
})
I want to make this as generic for all the request
Please share any sample,.. thanks in advance
I'm using something like this :
.factory('factoryResource', ['$resource', 'CONF',
function($resource, CONF) {
return {
get: function(endPoint, method) {
var resource = $resource(CONF.baseUrl + endPoint, {}, {
get: {
method: method || 'GET'
}
});
return resource.get().$promise;
}
};
}
])
called by :
factoryResource.get(CONF.testEndPoint, "POST"); // make a POST and return a promise and a data object
factoryResource.get(CONF.testEndPoint, "GET"); // make a GETand return a promise and a data object
factoryResource.get(CONF.testEndPoint); // make a GETand return a promise and a data object
with a config file having :
angular.module('app.constant', [])
.constant('CONF', {
baseUrl: 'http://localhost:8787',
testEndPoint: '/api/test'
});
I have a factory that returns the $resource for my Article model:
angular.module('ADI.Resources').factory("Articles", ['$resource', function($resource) {
return $resource('/api/v1/article/:articleId', {
articleId: '#_id',
_shop: window.user._shop
}, {
update: {
method: 'PUT'
}
});
}]);
GET, POST and DELETE are working well, but not the update (PUT). Here is the code I use:
Articles.update({articleId: '300000000000000000000001'}, function(article){
console.log(article);
});
It's making this request:
PUT http://localhost:3000/api/v1/article?_shop=100000000000000000000001
instead of:
PUT http://localhost:3000/api/v1/article/300000000000000000000001?_shop=100000000000000000000001
Any idea why the :articleId parameter is not filled when doing an update? Thanks!
As Fals mentionned in the comment, the articleId parameter was in the request content. So I made a little trick to have it also on the URI.
angular.module('ADI.Resources').factory("Articles", ['$resource', function($resource) {
return $resource('/api/v1/article/:articleId', {
articleId: '#_id',
_shop: window.user._shop
}, {
update: {
method: 'PUT',
params: {
articleId: "#articleId"
}
}
});
}]);
I had the same problem, the issue here was for the following line:
articleId: '#_id',
that line should be:
articleId: '#articleId',
articleId not need to be defined again.
I'm totally new to AngularJs and I have this problem I do not understand. I have two methods. The first one takes some data from a webservice and puts in in a variable defined in the scope. But when I want to use that variable in the second method it is undefined. Can someone help me understand why this is happening and provide a solution?
var myApp= angular.module( "myApp", [] );
myApp.controller("myAppController",
function( $scope ) {
$scope.getAll = function(){
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
url: ..something...,
success: function (parameters) {
$scope.profiles = angular.copy(parameters); <-- correct data is returned
$scope.$apply();
},
error: function () {
alert("Error calling the web service.");
}
});
}
$scope.getCategories = function(){
var all = $scope.profiles; <-- At this point profiles is empty
...
}
$scope.getAll();
$scope.getCategories();
}
Use the $http service and promises:
$scope.profiles = $http.jsonp(url).then(function(r){ return r.data; });
$scope.categories = $scope.profiles.then(function(profiles) {
var params = { }; // build url params
return $http.jsonp(url, { params: params }).then(function(r){ return r.data; });
});
When you call getCategories(), getAll() hasn't finished yet, which is why profiles is empty. There are several ways to solve this. The best way would be to use promises the built-in $http service.
If you prefer to use jQuery, you can add a watcher on the profiles variable and only when it's populated run the getCategories().
Something like this should work:
$scope.getAll = function(){
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
url: ..something...,
success: function (parameters) {
$scope.profiles = angular.copy(parameters); <-- correct data is returned
$scope.$apply();
},
error: function () {
alert("Error calling the web service.");
}
});
}
$scope.getCategories = function(){
var all = $scope.profiles;
}
// Wait for the profiles to be loaded
$scope.watch('profiles', function() {
$scope.getCategories();
}
$scope.getAll();
There is no guarantee that getAll has completed before getCategories is invoked, since it is an asynchronous request. So if you want to sequentially invoke getAll and getCategories, you should invoke getCategories inside the success callback of getAll. You could also look into promises for a neater way of chaining asynchronous callbacks (I assume you're using jQuery since you're calling $.ajax).
...
<snipped some code>
success: function(parameters) {
// snipped more code
$scope.getCategories();
}
(and if you're using jQuery promises)
$.ajax(ajaxCallOneOpts).then($.ajax(ajaxCallTwoOpts));
Neither are very "Angularish" though, so you might want to look into some of the provided services for working with http/rest resources instead of using jQuery.
Why are you using a jQuery ajax request in angular? If you write jQuery style code and wrap it angular, you're going to have a bad time...
Here is an angularised version:
myApp.controller("myAppController",
function( $scope, $q, $http ) {
$scope.getAll = function(){
var deferred = $q.defer();
$scope.profiles = deferred.promise;
$http.jsonp('your url').then(function(data) {
deferred.resolve(data);
});
});
$scope.getCategories = function(){
$q.when($scope.profiles).then(function(profiles) {
... <-- At this point profiles is populated
});
}
$scope.getAll();
$scope.getCategories();
}