$resource POST request with payload in angular - angularjs

I wanted to send a post request with a payload '{}' as required for the back end . I was using angular's $resource service and was not able to achieve this . Googling I happened to see that
method(param,payload) is the way to do that , but I could not make it work .
Below is my $resource factory
.factory('Dfs',['$resource',function($resource){
return $resource('http://'+server_ip+'/jax/search/',{},
{
query:{method:'POST'}
})}])
and in the controller I am calling
.controller('DFl', function($scope,Dfs){
var d={};
Dfs.query(d,function(resp)
{
console.log(resp);
}) })
The payload I want to send is
{}
please help .

I found one
ResourceName.method(payload,function(a,b){
//Handle the response here
})
That did work ... Thank You all ..

If you just want to send a simple POST request you can use the $http service.
var url = 'http://...';
var data = {};
$http.post(url, data).then(function(result) {
console.log(result.data);
});
Here is a simple demo.

Related

how to use $resource to get the data from local json file

I am trying multiple ways to access my users in a local json file in able to later compare them to the users input. and if there is a match, access is allowed, but my main problem now is just getting to those users.
My code so far:
entire code
json file
What am i doing wrong? i am such a newbie in programming. I have been trying different things and nothing works.
Thanks so much for help
Can you access the file through the browser (via your url localhost:8080/resources/data/users.json)?
If you can't, you will not be able to get access through the $resource or $http.
If you can, any method should work:
1) Via $resource
$scope.users = [];
var UsersResource = $resource('/resources/data/users.json');
where we can get response by callback
UsersResource.get({}, function(response) {
$scope.users = response;
});
or by $promise
UsersResource.get().$promise.then(function(response) {
$scope.users = response;
});
2) Via $http.get
$scope.users = [];
$http.get('/resources/data/users.json').then(function(response) {
$scope.users = response;
});
In your sample, your are trying to get array of users by returning $resource, but $resource returns a object with methods. Each method has callbacks (success, error) or return $promise object.
There is no need to use $resource if you are just going to fetch a json file. Use $http instead:
this.getUsers = function(){
return $http.get('path/to/file.json');
};
And usage:
dataService.getUsers().then(function(resp){
//Do something with the data
$scope.users = resp;
})
$resource is meant to be used when communicating with RESTful apis. What your getUsers() is doing is actually returning a resource-object, upon which you can then call get(). But I recommend using $http in this case.
If you want to use $resouce then you need to create two functions in your controller/factory where "templatesSuccess" return data of request.
getAllTemplates: function(query) {
return $resource(CONST.CONFIG.BASE_URL + 'receiver/get-templates').get(query, obj.templatesSuccess).$promise;
},
templatesSuccess: function(response) {
obj.allTemplates = response;
},

How can I parse this JSON response

I have the following JSON data being received by angularJS. It's being brought in from an ArrayList using a get request.
0: Object
id:1
area: "State"
gender: "Both"
highestEd: 3608662
.... etc
1: Object
id:2
area: "State"
gender: "Both"
highestEd: 3608662
.... etc
However I can't figure out how to access it using either a controller or the UI. I want to be able to store this data in Angular so I can then create graphs using the information. The only way I know it's definitely there is through looking at the response in firefox.
Any help / advice would be greatly appreciated.
Your JSON data is not in proper format. Use JSON lint to check
Use $http.get('/get_url/') to get the response . One sample example for this.
Once you have response in $scope.yourVariable use ng-repeat to loop over it
Take a look at this fiddler here you might get some ideas.
After calling the API using $http from you factory you will have resolve the data that you are getting. The controller needs to call the API method and then bind the resolved data from your factory to the API.
Factory
myApp.factory("Data", function($q, $http) {
return {
getData: function() {
var deferred = $q.defer();
/* --Actual API Call
$http.get("/url")
.then(function(response) {
deferred.resolve(response.data);
})
*/
//Dummy Data
var data = m;
deferred.resolve(data);
return deferred.promise;
}
}
});
Controller
function MyCtrl($scope, Data) {
Data.getData()
.then(function(items) {
$scope.bobs = items;
console.log($scope.bobs);
})
}
Replace the dummy data initialization from factory to the actual API call.

JWT: Getting token manually

I'm using jwt-auth for laravel, and angular-js on client side.
This is my typical http request:
.controller('LoginController', function($scope,$rootScope ,$auth, $state, $http, $timeout) {
$http.get('api/loggedIn/getMe').success(function(data) {
//do stuff
}).error(function(error) {
//do stuff
});
})
Every time i send $http request the token side is done automatically, but I want to make one request without using $http, so I need to include my jwt-auth token in headers manualy. (that's because I want to use Dropzone for file upload).
I have something like this:
Dropzone.options.myDropzone = {
sending: function(file, xhr, formData) {
// Pass token
xhr.setRequestHeader('Authorization', 'Bearer: ' + /*This is where I want to put my token*/);
}
};
Edit: this is screenshot from firebug:
Edit: I figured out that satelizer does that nice thing for me, so $auth.getToken() did the trick.
I figured out that satelizer does that nice thing for me, so $auth.getToken() did the trick.

angular-http-auth with $http transformResponse

I'm using angular-http-auth to show a login dialog whenever a 401 "unauthorized" response is returned from the server.
Since I'm cool, I also try to deserialize response objects in my services. For example, if a service requests a car and the response is {make: Honda, model: Civic}, I try to deserialize that into a Car object using transformResponse.
For example:
getCar: function() {
return $http.get('/api/car', {
method: 'GET',
transformResponse: function(data, headers) {
var c = angular.fromJson(data);
return new Car(c);
}
});
}
This doesn't work with angular-http-auth. If the response was a 401 Unauthorized, you'll get a javascript error. It's because angular will try to run that transformResponse code even if the response was a 401.
It turns out that $http interceptors (which is what angular-http-auth uses) are run AFTER the transformResponse code. That's a huge problem, because none of that code in transformResponse will work if the server response was a 401 (there wouldn't be any data)
Is this a problem for anyone else? How did you get around it? Am I not to use transformResponse if I use $http interceptors?
Late to the party, I know, but to anyone coming here from Google like I did (I also posted this as a comment on a related issue filed with the Angular repo):
I also found it to be confusing that response interceptors run after the transformResponse method. I added a method to $http.defaults.transformResponse. Here is an example from the documentation on how to do that.
So, if you need to basically have a response interceptor that runs before the transformResponse method, this should do it:
'use strict';
angular.module('app')
.run(function ($http) {
$http.defaults.transformResponse.push(function (data, headers) {
// do stuff here before the response transformation
// Be sure to return `data` so that the next function in the queue can use it.
// Your services won't load otherwise!
return data;
});
});
If your services or http calls don't have their own response transformer, you're good now.
If your services do have their own transformResponse method, they will actually override all default transformers (I found this out after a long read of the documentation), and the above code will not run.
To circumvent this, you can follow this example in the docs.
To get around this problem I don't use transformResponse anymore. I just can't see the point of transformResponse if it runs before $http interceptors.
In order to use angular-http-auth and also deserialize responses in your services, you can write your services so that they execute the HTTP request first and then deserialize the response in a callback function.
As an example, here is how I would have restructured the example in the OP:
Plunker
services.factory('HttpCarService', function($resource, $q) {
var resource = $resource('/api/car');
return {
getCar: function() {
var deferred = $q.defer();
var car = null;
var successCallback = function(data, status, headers, config) {
var c = angular.fromJson(data);
car = new Car(c);
deferred.resolve(car);
};
var errorCallback = function(data, status, headers, config) {
deferred.reject("something wrong");
};
var result = resource.get(successCallback, errorCallback);
return deferred.promise;
}
};
});
This pattern will also work if data is an array.
$http interceptors will run before either of the callback methods are executed. If your $resource needs url params, you can make the getCar() function accept a config object as a parameter, and pass the necessary information on when you make the $resource.get() call.

POST Behavior Between $http and Restangular

I have a simple ASP.NET Web API 2 service. I'm new at Angular, but I'm trying to switch from using $http to Restangular. My GET appears to be fine, but my POST is not.
The code looks like this:
$scope.addLift = function () {
$http.post(url, $scope.Lift);
//Restangular.all('lifts').post('Lift', $scope.Lift).then(function (newLift) {
// $scope.getLifts();
//}, function (error) {
// console.log(error);
//});
};
The commented out Restangular code does not work, but the $http.post does and I'm not sure what I'm doing wrong.
If it's helpful, the POST when using Restangular is http://localhost/api/lifts?LiftName=test where in the $http POST request, it does not contain the parameters on the URL line, it seems the data is in the request body.
Someone on another website was kind enough to help me through this. Thought I would post the answer in hopes that it might benefit others.
Restangular.all('lifts').post($scope.Lift).then(function (newLift) {
$scope.getLifts();
}, function (error) {
console.log(error);
});
The additional 'lift' argument was not necessary in the post call.

Resources