How do I pass parameter to an angular service? - javascript

I have made simple HTTP based API and I would like to make POST calls to it like:
http://mysite.com/api/v1/person/something
http://mysite.com/api/v1/person/else
http://mysite.com/api/v1/person/someword
in general
http://mysite.com/api/v1/person/<word>
In angular I have created a service
angular.module('personService', ['ngResource']).
factory('Person', function($resource){
return $resource('/api/v1/person/:word', {}, {
action: {method:'{POST', params:{ ???? }, isArray : false},
});
});
And in my controller which uses the service I would like to be able to call Person.action() and pass it a parameter to determine what word is, for example:
Person.action('something', function(d) {
console.log('Result of api/v1/person/something')
});
but I'm not sure how to connect the two. See ???? in the third code block.

Try this:
params:{ word: '#inputWord' }
Person.action({inputWord: 'somethings'}, function(d) {
console.log('Result of api/v1/person/something')
});
word matches the :word variable in the url and the passed in object's key inputWord matches #inputWord.

Related

How to access sub objects of an object returned by AngularJS data service inside controller

I have an angularjs data factory that makes a server call and sets the returned data in the factory returned object like this
angular.module('app').factory('DataService', function() {
// Returning object
return {
data: {},
isLoaded: false,
getData:getdata
};
function getData() {
var self = this;
//Some Ajax Call returns an 'dataObject'
self.data = dataObject; //dataObject has a few subObjects and list
}
});
Now inside my angularjs controller I am making call to the DataService.getData() to make ajax call and hence set the returned dataObject within factoryobject 'data'
and I have declared it in controller like this
appV.data = DataService.data;
If I try to print it on console or access like this
console.log(appVm.data), I am able to access it, but if I try to access any subObjects like Ex - appVm.data.property1 or appVm.data.subObject1.subObject1.property, it gives undefined.
Can someone please explain why this behavior is occuring ?
Thanks in Advance
It is just example:
app.factory("messageService", function($q){
return {
getMessage: function(){
return $q.when("Hello World!");
}
};
});
And now the routing configuration that will use the service in a resolve.
$routeProvider
.when("/news", {
templateUrl: "newsView.html",
controller: "newsController",
resolve: {
message: function(messageService){
return messageService.getMessage();
}
}
})
These link may help you:
Link 1,
Link 2

Angular: Pass params to $http.get

I'm trying to pass a params object to the $http.get() service. My params look like this:
var params = {
one: value,
two: value
}
And I'm trying to pass them into my function like so:
$http.get('/someUrl', params)
.success(function(data) {
// stuff
})
.error(function(data) {
// error stuff
});
Is this the correct way to go about doing this?
The second argument of $http is a config object (see documentation). Amongst other properties, the config object accepts a params property:
params – {Object.<string|Object>} – Map of strings or objects which will be serialized with the paramSerializer and appended as GET parameters.
Therefore you have to pass the parameters as such
var config = {
params: {
one: value,
two: value
}
}
$http.get('/someUrl', config).then(...)
Suppose the values for the parameters are respectively '1' and '2', $http will send a GET request to the following url:
/someUrl?one=1&two=2
As a side note, try to avoid using success and error functions on $http. They have been deprecated as of angular 1.4.4. Use the methods then with a success and an error callback instead, or then with only a success callback and catch.
Service/Factory
For the actual call use a factory or service that you can inject to the controllers you need it in. This is an example factory passing parameters
.factory('Chats', function ($http, $rootScope, $stateParams) {
return {
all: function () {
return $http.get('http://ip_address_or_url:3000/chats', { params: { user_id: $rootScope.session } })
}
};
});
Controller
In your controller you use the service like this
.controller('ChatsCtrl', function ($scope, Chats) {
Chats.all().success(function (response) {
$scope.chats = response;
})
})
I have faced similar issue in recent time and I had to add few additional details to request (I used accepted answer with some headers):
$http.get(url, {
params: {
paramOne: valueOne,
paramTwo: valueTwo,
...
},
headers: {
'key': 'value'
},
// responseType was required in my case as I was basically
// retrieving PDf document using this REST endpoint
// This is not required in your case,
// keeping it for somebody else's reference
responseType: 'arraybuffer'
}).success(
function(data, status, headers, config) {
// do some stuff here with data
}).error(function(data) {
// do some stuff here with data
});
The $http documentation suggest that the second argument to the $http.get method is an object which you can pass with it "param" object.
Try something like this:
$http.get('/someUrl', {params: params})
.success(function(data) {
// stuff
})
.error(function(data) {
// error stuff
});

Angular $resource remove question mark from REST querystring

Hi i was wondering if anyone could help me change the format of my querystring. Currently it is in the following format:
/api/foo?id=AD12JK23
but how would I go about to changing it to the following format:
/api/foo/AD12JK23
my code is as follows:
.state('foo-details', {
url: '/foo-details/:fooRefrence'
}
})
var ref = $stateParams.fooRefrence;
$scope.fooDetails = myApi.Foo.get(
{
id: ref
}
);
.factory('myApi', ['$resource', function ($resource) {
return {
Foo: $resource('/api/foos', {id: '#ref' },
}
}])
Thanks for any help.
Check out the resource reference for the appropriate way to do this.
https://docs.angularjs.org/api/ngResource/service/$resource#usage
I think if you write your resource url like this, it will solve the problem:
.factory('myApi', ['$resource', function ($resource) {
return {
// Add :id at the end of the url
// Also change #ref to #id, the word you use after # is the same as
// the key of the object you use to call the resource with
Foo: $resource('/api/foos/:id', {id: '#id' },
}
}])

AngularJs ngResource for nested api resurces with different endpoints

I have this endpoints
/clients/:id
/bills/:id
/clients/:id/bills
I'm trying to create some resources with angular-resource to represent my API.
Clients and Bills Resources
I created a resource for the clients,
.factory('Clients', function($resource){
return $resource('/clients/:id')
})
.factory('Bills', function($resource){
return $resource('/bills/:id')
});
Those worked fine.
The Problem
My problem is when I wanted to define a resource to represent the bills of a client calling the endpoint /client/:id/bills
I thought that this should be a Bills resource with a method getFromClient() or something like that, as it will return an array of Bills from the client. But I have already use the Bills name. And the endpoint is different to the one already defined.
Any idea how to structure this?
I think what I was loooking for is now in Anguar 1.1
.factory('Bills', function($resource){
return $resource('/bills/:id',{}, {
get: {
method: 'GET',
params:{
clientId: '#clientId'
}
},
'getFromClient': {
method:'GET',
params: {
clientId: '#clientId'
},
url: host + "/clients/:clientId/bills",
isArray: true
}
})
});
Now you can add a url property to the method declaration to override the main url.
If you want to go with a library that enable you to solve this problema and many others, you could try https://github.com/platanus/angular-restmod
Here is an example:
.factory('Client', function(restmod){
return restmod.model('clients', {
bills: { hasMany: 'Bill' }
});
}
.factory('Bill', function(restmod){
return restmod.model('bills');
}
.controller('myController', function(Client){
$scope.client = Client.$find(1);
$scope.client.bills.$search();
});
Check the ngResource docs... Scroll down to the first example heading:
http://docs.angularjs.org/api/ngResource.$resource
It's kinda confusing because they're not doing it right in the example... lol
I believe it would look something like:
.factory('Clients', function($resource){
return $resource('/clients/:id', {id:'#id'})
})
.factory('ClientBills', function($resource){
return $resource('/clients/:clientId/bills/:id', {clientId:'#clientId', id:'#id'})
});
I haven't tested this, but I think that's right. =)
UPDATE
You would then access them like so:
.controller('MyCtrl', function ($scope, $routeParams, Clients, Bills) {
$scope.client = Clients.get({id:$routeParams.clientId})
$scope.bills = ClientBills.get({clientId:$routeParams.clientId})
})
I also changed the name of the service to "ClientBills", as it is more specific to the task, and you may want a "Bills" service that doesn't require a client id...

Using AngularJS $resource to get data

I am trying to use $resource to get data from a static json file and here is the code snippet :
angular.module('app.services', ['ngResource']).
factory('profilelist',function($resource){
return $resource('services/profiles/profilelist.json',{},{
query:{method:'GET'}
});
});
In the controller,
function ProfileCtrl($scope,profilelist) {
$scope.items = [];
$scope.profileslist = profilelist.query();
for (var i=0;i<=$scope.profileslist.length;i++){
if($scope.profileslist[i] && $scope.profileslist[i].profileid){
var temp_profile = $scope.profileslist[i].profileid;
}
$scope.items.push(temp_profile);
}
But now, I am facing an error :
TypeError: Object #<Resource> has no method 'push'
Could you please help me where I am going wrong ?
You don't need to specify actions parameter for default $resource methods (these are 'get', 'save', 'query', 'remove', 'delete'). In this case you can use .query() method as is (this requires only service definition to be chaged):
angular.module('app.services', ['ngResource']).
factory('profilelist',function($resource){
return $resource('services/profiles/profilelist.json');
});
P.S. And one more hint is that your example unwrapped json into hash rather then array (that's why you received no push method error), if you need it to be an array set isArray: true to action config:
'query': {method:'GET', isArray:true}
And as #finishingmove spotted you really can't assign $resource result to obtain immediately, provide callback:
$scope.profileslist = profilelist.query(function (response) {
angular.forEach(response, function (item) {
if (item.profileid) {
$scope.items.push(item.profileid);
}
});
});

Categories