GET Request Without Key in URL - Angular JS - angularjs

I have a GET endpoint like the following:
http://test.com/api/test/1234
where 1234 is the value of the key. The URL only looks for the value of the key and not the key name itself.
I tried using:
var params = {'': vehicleId};
to set the parameter, but the resulting URL looks like:
http://test.com/api/test?=237819
How do I hit my API in the above format using Angular's $Resource .get() method?

The resource has to be defined as:
var Vehicle = $resource('/api/test/:vehicleId', { vehicleId: '#id' });
and then the resource can be used as:
Vehicle.get({vehicleId: 1234}, function(data) {
console.log("data", data);
});

Related

Calling REST API with parameter

I'm trying to create a product browser. I wrote simple HTML view code with a text field, button and result list. I also wrote REST API GET method with the parameter which query objects by ID. Url of my view is #/Products but REST method URL #/Products/Id
REST GET
#Path("/{id:[0-9][0-9]*}")
#Produces("application/json")
public Response findById(#PathParam("id") Long id) {body}.
Now I'm trying to write controller to #/Product view
angular.module('searchingPage').controller('SearchProductsController', function($scope, $http, $filter, ProductResource ) {
$scope.search={};
$scope.performSearchById = function() {
//goal $scope.searchResults = ProductResource.findById($scope.search.id);
};
})
How can I call my REST API with parameter and right path with Id in it?
the '#' sign use for client side not server side, your rest method url is probably something like "api/Products/Id". you can simply call rest method as below
$scope.performSearchById = function() {
$http({
url: 'api/Products/' + $scope.search.id,
method: 'GET'
}).then(function(data){
$scope.searchResults = data.data;
})
};
}

How to contact a non-standard API using Angular ngResource

The API I am using requires a non-standard where clause if I try to search for a particular non-id field. The endpoint I need is:
http://127.0.0.1:4001/api/testusers/findOne?userName=Anton
So this will find me the first record in the testusers table whose column (userName) = 'Anton'.
My standard service is:
angular.
module('shared.testUser').
factory('TestUser', ['$resource',
function($resource) {
return $resource('http://127.0.0.1:4001/api/testusers/:id', {id:'#id'},//parameters
{
update: {
method: 'PUT' // To send the HTTP Put request when calling this custom update method.
}
});
}
]);
and my calling function is:
self.checkUsersEntryDirection = function(){ //NOT WORKING
self.testuser = TestUser.get({ username: 'anton' }, function() {
console.log(angular.toJson(self.testuser));
}); // get() returns a single entry
}
Clearly this doesn't work and I can't use the standard get approach. Can anyone think how this can be achieved?
You could create a secondary factory TestUserByName, and make the following changes:
angular.
module('shared.testUser').
factory('TestUserByName', ['$resource',
function($resource) {
return $resource('http://127.0.0.1:4001/api/testusers/findOne?userName:username', null,
{
update: {
method: 'PUT' // To send the HTTP Put request when calling this custom update method.
}
});
}
]);
Call the get action method with two parameters:
var params = {id: "findOne", username: "anton"};
self.checkUsersEntryDirection = function(){
self.testuser = TestUser.get(params, function() {
console.log(angular.toJson(self.testuser));
}); // get() returns a single entry
}
The id parameter will override the default and username parameter will be added as a query string.
From the DOCS:
Each key value in the parameter object is first bound to url template if present and then any excess keys are appended to the url search query after the ?.
Given a template /path/:verb and parameter {verb:'greet', salutation:'Hello'} results in URL /path/greet?salutation=Hello.
--AngularJS ngResource $resource Service API Reference

unable to retrieve request param in node js

In my angular js factory, i am making an ajax call to transfer the input model value to the server side ( node js) but when i try to retrieve it , i see 'undefined' .
angular js :
angular.module('name-App').factory('myService', function($http,$rootScope) {
return {
getFoos: function(stock) {
console.log("----------->"+stock.toString());//displays the value correctly over here .
//return the promise directly.
return $http({
url:'http://localhost:3000/gethistorydata',
method: "GET",
params: stock
}).then(function(result) {
alert("result.data"+result.data);
return result.data;
}).catch(function(fallback) {
alert("failed"+fallback + '!!');
});
}
}
});
In node js i have below :
app.get('/gethistorydata',function(req,res){
console.log("--------------->>>>>>");
console.log("stock name = "+req.params.data);
//res.cookie();
//res.sendFile("F:/customer/public/index.html");
});
req.params.data is undefined . whats wrong with syntax?
req.params refers to url path parameters. So you would have to add one to your route for it to be supported. For example a request to /gethistorydata/123 with this route defined(note the added /:id on the end):
app.get('/gethistorydata/:id, function(req, res) {
console.log('my id is ' + req.params.id');
});
would log "my id is 123".
I think you are looking for req.query. What does your stock object look like? If it looked like this {"price": 123} angular would modify the request to look like /gethistorydata?price=123 and you could change your code to this:
app.get('/gethistorydata, function(req, res) {
console.log('my stock price is ' + req.query.price');
});
which would log "my stock price is 123"
See the docs for more examples http://expressjs.com/en/api.html#req.query

Using [] square brackets as part of a parameter in $resource GET call to API in Angular is not working

I am trying trying to GET user data from an ajax-localized REST api that wants parameters like so:
/api/activity?filter[user_id]=1
I have a factory set up with query parameters like so:
angular.module('app')
.factory('Activity',function($resource){
return $resource(ajaxInfo.api_url+'activity',
{ // Query parameters
filter: {
'[user_id]': '#userId'
},
},
{
'query':{
method:'GET',
headers: {
'X-WP-Nonce': ajaxInfo.nonce
},
isArray: false
}
});
})
I'm console.logging it in a template like so:
$scope.userOne = Activity.query({userId:1});
console.log($scope.userOne)
It's returning
http:site.dev/api/activity?filter=%7B%22%5Buser_id%5D%22:%22#userId%22%7D&userId=1".
Any idea what I'm doing wrong?
Here's what I did to fix this:
I created a factory called "CurrentUser" this factory basically returns the current user's object from an api.
Then I created a controller that passed the parameters to the Activity factory when I wanted to filter the activity by that user id.
$scope.userInfo = function(){
//call the CurrentUser and see if it's available and return it as u
CurrentUser.instance().then(function(u) {
//now query the activity factory and pass the filter as a string along with the user id as u.id
Activity.query({'filter[user_id]':u.id}, function(res){
$scope.userOne = res ;
console.log($scope.userOne);
});
})
};
$scope.userInfo();

How to get URL parameter in Express?

I have a problem with getting URL parameter in Express.
On the client (Angular) I define state (ui.router) and send URL (id) with new state:
.state('home.detail', {
url: '/:id',
templateUrl: 'views/detail.html',
controller: 'DetailController'
});
On the backend, I'm trying to get this URL(id)
app.get('/api/:id', function(req,res){
var id = req.query.id;
console.log(id);
var queryString = "SELECT * FROM `table` WHERE table.ID=id";
//add to a callback
connection.query(queryString, function (error, results) {
if(error) {
throw error;
}
else {
// send JSON object to the client
res.end(JSON.stringify(results));
//console.log(res);
}
});
});
but I got undefinedvalue of id (console.log(id)).
What I'm doing wrong?
You should use this instead :
var id = req.params.id;
req.params contains route parameters (in the path portion of the
URL)
req.query contains the URL query parameters (after the ? in
the URL).
The :id gets put in the params object in the request. So, all you have to do to get it is do:
var id = req.params.id;
Also, when you build your queryString you need to pass it the value of id instead of a string called "id". You would have to do something like this:
var queryString = "SELECT * FROM `table` WHERE table.ID=" + id;

Resources