How to retrieve objects from rest url with multiple parameters using angular - angularjs

How can i create a factory that can retrieve data from
/rest/company/:companyid/employee/:id
when i use this url in the factory I get an error: Unknown provider companyidProvider
Thank you,
Kyle
Service:
app.factory('EmployeeByCompany', function ($resource,companyid) {
return $resource('app/rest/company/:companyid/employee/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': { method: 'GET'}
});
});
I'm guessing the error is from having the companyid as a parameter with $resource. What is the right way for a service to call this url?

If you are learning or geting started, try Restangular https://github.com/mgonto/restangular

Related

add config in angular resource

I am using http-auth-interceptor for authentication. In http-auth-interceptor, I use the following way to login:
var data = 'username=' + encodeURIComponent(user.userId) + '&password=' + encodeURIComponent(user.password);
$http.post('api/authenticate', data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
ignoreAuthModule: 'ignoreAuthModule'
})
ignoreAuthModule is used to tell ignoreAuthModule that this login method will be ignored by the auth interceptor.
Now, I have some request with $resource, like:
.factory('SomeDataService', function ($resource) {
return $resource('api/some/data', {}, {
'get': { method: 'GET'}
});
})
I want SomeDataService.get() is also ignored by the auth interceptors, because I need to control the 401 error by myself.
So, my question is, is there any way for ngResource that I can set config like that in $http.
[update based on comment]
I have listened the login-required event:
$rootScope.$on('event:auth-loginRequired', function (rejection) {
$log.log(rejection);
// I need to get the request url and for some specific url, need to do something.
$rootScope.loginPopup();
});
But the 'rejection' parameter has no context data of request I need. I need to get the request url and check, for some specified url, I need to do something.
After checking the document of ngResource, I got the solution as below:
.factory('SomeDataService', function ($resource) {
return $resource('api/some/data', {}, {
'get': { method: 'GET', ignoreAuthModule: 'ignoreAuthModule'}
});
})
Just add the config item as above. It will be equivalent ad:
$http.post('api/some/data', data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
ignoreAuthModule: 'ignoreAuthModule'
})
ngResource module is build on top of $http.Hence it is not possible to configure all the stuffs you can do with $http in $resource.I think the below link will be guide you to have a clear understanding on $http and $resource

Angular ngResource post with API key

I am using the Code Igniter REST library to serve my api. I am trying to protect my api to keyed access. I can successfully retrieve info in my application using ngResource and the key however I am getting a 403 refusal when trying to post with the same key. For now I am simply embedding the key in my factories.
Here is my successful factory:
.factory('Breweries', ['$resource',
function($resource) {
var key = '621d004e78de5b1ef9c634ae3fc9b84a';
return $resource('http://restapi.dev/api/breweries?key=' + key, {}, {
query: {
method: 'GET',
isArray: true
},
});
}
])
And the unsuccessful factory:
.factory('Claim', function($resource) {
var key = '621d004e78de5b1ef9c634ae3fc9b84a';
var Claim = $resource('http://restapi.dev/api/system/:method?key=' + key, {}, {
save: {
method: 'POST',
params: {
method: 'claim'
}
},
send: {
method: 'POST',
params: {
method: 'contact'
}
}
});
return Claim;
})
Both factories work and function properly without the key so I am not far off. I appreciate any help. I believe I am using resource a little improperly for this however I have only found references to submitting the key as a header and not a query.
An interceptor is simply a regular service factory that is registered to that array. Using AngularJS interceptors with $http
https://docs.angularjs.org/api/ng/service/$http#interceptors

AngularJS Response does not match configured parameter

I've got a problem with service configuration. I want to display one user by this function:
$scope.findOne = function() {
$scope.user = Users.get({
userId: $stateParams.userId
});
};
But I am in trouble with User service :( I don't know, how should I change my the code to avoid angular error:
Error in resource configuration for action object. Expected response
to contain an array but got an {2}
Here is a code of my actual working service (without function findOne working of course:))
'use strict';
angular.module('users').factory('Users', ['$resource',
function($resource) {
return $resource('users', {}, {
update: {
method: 'PUT'
},
remove: {
method: 'DELETE',
url: 'users/:id',
params: {id: '#_id'}
}
});
}
]);
At a guess, I'd say your users API endpoint is expecting /users/:userId for GET requests. Your code at the moment will request /users?userId=nnn. You need to add an action for get with the ID in the URL, eg
return $resource('users', {id: '#userId'}, {
get: {
method: 'GET',
url: 'users/:id',
isArray: false
},
// etc
You can also make users/:id the default URL as long as it doesn't interfere with your other action configurations.

AngularJS Custom Resource URL being overwritten

I have a custom resource defined as such:
app.factory('SpaceGroupService', ['$resource', function ($resource) {
return $resource('api/SpaceGroup/:id', { id: '#id'},
{
'parkingSpaces': { method: 'GET', url: 'api/SpaceGroup/:id/ParkingSpaces', isArray: true }
});
}]);
The idea is to pass in an ID of my space group object to return all parking spaces in that group. When I call
SpaceGroupService.query()
While running on my local iisexpress it's hitting the correct service url:
/api/SpaceGroup
But when I do:
spaceGroup.$parkingSpaces({ id: spaceGroup.SpaceGroupId }, function (parkingSpaces) {
spaceGroup.parkingSpaces = parkingSpaces;
});
It is querying my restful service as:
/api/SpaceGroup/2
instead of:
/api/SpaceGroup/2/ParkingSpaces
I'm somewhat new to angularJS and I know my route works on my API controller so I'm just trying to get this service to work properly. Any ideas why this overwritten URL isn't called?
I'd would write your service like this instead:
app.factory('SpaceGroupService', ['$resource', function ($resource) {
return
{
ParkingSpaces: $resource('api/SpaceGroup/:id/ParkingSpaces', {},
{
query: { method: 'GET', params: { id: '#id'}, isArray: true }
}
}
}]);
And then call it like this instead:
SpaceGroupService.ParkingSpaces.query({ id: someId });
You can set up multiple resources in the service this way - and you can define multiple methods too (GET, POST, PUT, DELETE). It also means that Angular will honor your $resource url.

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

How fix Error:
[$resource:badcfg] Error in resource configuration. Expected response
to contain an array but got an object?
// Service
angular.module('admin.services', ['ngResource'])
// GET TASK LIST ACTIVITY
.factory('getTaskService', function($resource) {
return $resource('../rest/api.php?method=getTask&q=*',{ 'get': {method:'GET'}});
})
// Controller
$scope.getTask = getTaskService.query(function (response) {
angular.forEach(response, function (item) {
if (item.numFound > 0) {
for(var i = 0; i < item.numFound; i++) {
$scope.getTasks[i] = item.docs[i];
}
}
});
});
Also, if your service is sending an object instead of an array add isArray:false to its declaration.
'query': {method: 'GET', isArray: false }
$resource("../rest/api"}).get();
returns an object.
$resource("../rest/api").query();
returns an array.
You must use :
return $resource('../rest/api.php?method=getTask&q=*').query();
First of all you should configure $resource in different manner: without query params in the URL. Default query parameters may be passed as properties of the second parameter in resource(url, paramDefaults, actions). It is also to be mentioned that you configure get method of resource and using query instead.
Service
angular.module('admin.services', ['ngResource'])
// GET TASK LIST ACTIVITY
.factory('getTaskService', function($resource) {
return $resource(
'../rest/api.php',
{ method: 'getTask', q: '*' }, // Query parameters
{'query': { method: 'GET' }}
);
})
Documentation
http://docs.angularjs.org/api/ngResource.$resource
In order to handle arrays with the $resource service, it's suggested that you use the query method. As you can see below, the query method is built to handle arrays.
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
User $resource("apiUrl").query();
Make sure you are sending the proper parameters too. This happened to me after switching to UI-Router.
To fix it, I changed $routeParams to use $stateParams in my controller. The main issue was that $stateParams was no longer sending a proper parameter to the resource.
For anyone coming here in 2021, another way this request may look is as follows (at least it was in our app)
angular.module('load').factory('StateService', ['$resource', 'store', function($resource, store) {
return $resource('/some/url', {}, {
fetchAllStateCodes: {
method: 'GET',
isArray: true, // Response is an array of objects
headers: {
"Authorization": "Bearer " + store.get("jwt"),
"Content-type": "application/json"
}
}
});
}]);
From all of the good answers, it still wasn't obvious to me as to where to put the isArray flag...

Resources