I am adding a pair of actions to an AngularJS resource, but when I invoke the action, my transformRequest function is not getting called:
var _resource = $resource('api/NewItem/:id',
{ id: '#id' },
{
create: {
method: 'POST',
transformRequest: function (data, headersGetter) {
var result = JSON.stringify(data.productIntro);
return result;
}
},
update: {
method: 'PUT',
transformRequest: function (data, headersGetter) {
var result = JSON.stringify(data.productIntro);
return result;
}
}
});
If I add the function globally on the app, it works:
var newItemApp = angular.module('newItemApp', ['ngResource'])
.config(function ($httpProvider) {
$httpProvider.defaults.transformRequest = function(data)
{
if (data === undefined) {
return data;
}
var result = JSON.stringify(data.productIntro);
return result;
};
});
What I need to do is remove the root element from any POST or PUT action because the default model binding in Web Api does not bind a json object when that object has a named root.
transformRequest is supported since AngularJS 1.1.2. If you use early version, you need to add it to $httpProvider.
Related
Hey I want to change the data before sending it with ngResource (build FormData object). I do everything as in the examples that I found, however I can't make them work. Here is my code:
My controller where I set the data and try to send them:
var vm = this;
vm.application = new Application();
vm.application.title = 'Test title';
Application.save({}, vm.application, function(){
});
My service:
function application(ApiBaseUrl, $resource) {
var actions = {
'save': {
metod: 'POST',
url: ApiBaseUrl + "/applications",
headers: { 'Content-Type': false },
transformRequest: function (data) {
console.log(data); //Returns 'undefined'
return data;
}
}
};
return $resource(ApiBaseUrl + "applications/:id", {}, actions);
}
In the function transformRequest data object is always marked as 'undefined'. Am I doing something wrong? Is there a better way to edit the data before sending it?
The problem was I had
metod: 'POST'
when I should have used:
method: 'POST'
i have
$http({
url: 'http://webapi.-----UA_WebApi/GetUserAccount',
method: 'POST',
params: {Username:Username, Password:Password},
headers: { 'Content-Type': 'application/json;charset=utf-8' },
})
and in my service i wrote this method :
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
if anyone could help me understand what i am doing (right and wrong) pls ?
i would also like an example in how to use the angular resource for post.
the PostLogin works
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
.then(function (results) {
if(results.data.TotalRows==1) {}
TotalRows is undefined when debugging. but there is TotalRows in the api
thanks
var actions = {
post: {
method: 'post',
transformResponse: function(data) {
// here is your chance to change received data
return new Model(angular.fromJson(data));
}
}
};
var url = "http://postSomeData/:id/somethingElse/:name";
var parameters = { id : 1, name : "test" }
var data = { name : "test", type : "some type" };
return $resource(url, parameters, actions).post(data).$promise;
I have a model that I am using to hold my data in angular:
var FuelProcessingModel = function (carrierService) {
this.myArray = [];
};
That model has an array of MyObjects that I get from the DB:
var MyObject = function () {
//stuff
}
I update this using a REST call:
$scope.add = function () {
var myObject = new MyObject();
$scope.model.MyObjects.push(myObject);
service.add(myObject);
};
Which I use a service to hit the Server:
this.add = function (myObject) {
$http({
method: "POST",
url: "theServer",
data: myObject
});
}
The REST service just adds to the database, It doesn't return anything.
I need to reload the data from the database after the update is finished, so that my records now have all newly associated ID's and pertinent data.
I cannot just do:
window.location.reload();
The user starts by selecting a value from a drop down list to decide which list of data they start off seeing. I cannot / do not want to pass the value to it, mainly because it is in its own partial view, with its own controller, because it is used on many pages.
I tried doing:
$scope.add = function () {
//same as above
//this
service.get().then(function(result) { $scope.model.myArray = result.data; });
};
Obviously the problem here is the promise isn't complete before the DOM reloads the page. So the user saw themself add an item to the array and it vanished.
Do I want to load the page after the promise is complete? (How would I do that?)
should I return the updated data from the REST service and reset the current value? (seems like the same promise issue)
Is there a better practice that I do not know about?
UPDATE
For Bergi:
this.get = function (key) {
return $http({
method: "GET",
url: "theServer" + key
})
.success(function (data) {
return data;
});
}
I think you want to chain your two promises:
$scope.add = function () {
var myObject = new MyObject();
$scope.model.MyObjects.push(myObject);
return service.add(myObject).then(function() {
return service.get();
}).then(function(result) {
$scope.model.myArray = result.data;
});
};
and
this.add = function(myObject) {
return $http({
// ^^^^^^ return a promise here
method: "POST",
url: "theServer",
data: myObject
});
};
You can wrap your service call in a deferred promise, and on return success re-init your data from the controller..
$scope.add = function () {
var myObject = new MyObject();
$scope.model.MyObjects.push(myObject);
service.add(myObject).then(function (response) {
// here's where you'd do whatever you want to refresh your model
}),
function (err) {console.log(err);};
};
And the service:
this.add = function (myObject) {
var deferred = $q.defer();
$http({
method: "POST",
url: "theServer",
data: myObject,
success: function (response) {
deferred.resolve(err);
},
error: function (err) {
deferred.reject(err);
}
});
return deferred.promise;
}
I have a HTTP based RESTful APIs
When i connect for example to www.domain.com/chiamate/ELSENWZ i got this result:
{
"TICKET": "155112-I",
"TICKET_2": "ATRE6463",
"ACCOUNT_NAME": "PIPPO",
"CUSTOMER_NUMBER": "AG5",
"PROBLEM_TYPE": "H",
"VENDOR": "ITALWARE-CON",
"DESCR": "HP 6300 PRO SFF",
}
I have implemented into AngularJS a service to use the rest api in this way:
var services = angular.module('ngdemo.services', ['ngResource']);
services.factory('ChiamataFactory', function ($resource) {
return $resource('/chiamate/:id', {}, {
show: { method: 'GET',
isArray: false, // <- not returning an array
transformResponse: function(data, headers){
var wrapped = angular.fromJson(data);
alert(JSON.stringify(wrapped, null, 4));
angular.forEach(wrapped.items, function(item, idx) {
wrapped.items[idx] = new Post(item); //<-- replace each item with an instance of the resource object
});
return wrapped;
} },
create: { method: 'POST' },
update: { method: 'PUT', params: {id: '#id'} },
})
});
because i want that when the controller use the service,
$scope.chiamata = ChiamataFactory.show({id: 'ELSENWZ'});
into result i need to add some extra properties.
The problem is that the service don't use the transformResponse
It is not possible to use the transformResponse to decorate the data with data from an asynchronous service
Try this pseudo-code
angular.module('myApp').service('MyService', function($q, $resource) {
var getResult = function() {
var fullResult = $q.defer();
$resource('url').get().$promise.then(function(data) {
var partialPromises = [];
for (var i = 0; i < data.elements.length; i++) {
var ires = $q.defer();
partialPromisses.push(ires);
$resource('url2').get().$promise.then(function(data2) {
//do whatever you want with data
ires.resolve(data2);
});
$q.all(partialPromisses).then(function() {
fullResult.resolve(data);
});
return fullResult.promise; // or just fullResult
}
});
};
return {
getResult: getResult
};
});
or you can use transformResponce with $http as described in the documentation
angular $http documentation
How to make angularjs $resource return an array of objects derived/prototyped from specified domain object?
Here is an example on http://plnkr.co/edit/AVLQItPIfoLwsgDzoBdK?p=preview that processes a set of Notes objects.
app.controller('MainCtrl', function($scope, NoteResource) {
$scope.name = 'World';
$scope.notes = NoteResource.query();
$scope.spellCheckAllNotes = function() {
angular.forEach($scope.notes, function(note) {
note.spellCheck();
});
}
});
The issue is that $resource returns array of Resources and not an array of Notes with Resource methods added to prototypes.
[solution shall follow "good" javascript practices]
Here is the completed plunker. Yes raw json is parsed to JSON object. It is using transformResponse as mentioned by Armando.
app.factory('NoteResource', ['$resource',
function($resource) {
var res = $resource('http://okigan.apiary.io/notes/:id', {}, {
query: {
method: 'GET',
params: {
},
isArray: true,
transformResponse: function(data, header){
//Getting string data in response
var jsonData = JSON.parse(data); //or angular.fromJson(data)
var notes = [];
angular.forEach(jsonData, function(item){
var note = new Note();
note.noteTitle = item.title;
notes.push(note);
});
return notes;
}
}
});
return res;
}
]);
Just to show title is not used from the raw resource, I modified title to noteTitle in Note and in html.
You can manipulate your data using transformResponse option in your resource service definition (make sure to set isArray to true):
angular.module('services', ['ngResource']).
factory("yourService", function ($resource) {
return $resource(
'/custom/url', {}, {
get: {
method: 'GET',
isArray: true,
transformResponse: function(data, headers){
//
// transform to array of objects
return data;
}
}
}
);
});