ngResource, pass params into transformRequest function - angularjs

Given:
Users = $resource apiUrl+"/v1/users/?offset=:offset&limit=:limit&format=json", {},
getNext:
method: 'GET'
Users.getNext { offset:20, limit:20 }, (data)->
console.log "got some data"
Instead of explicitly passing offset and limit, I'd like to pass current set and in transformRequest function extract limit and offset and set those parameters for the http call. How can I do it?
Doing something like that not working:
Users = $resource apiUrl+"/v1/users/?offset=:offset&limit=:limit&format=json", {},
getNext:
transformRequest: transformReq(data)
transformReq = (data)->
console.log "data == "+data
and even this doesn't:
transformReq = (data)->
[
(data) ->
console.log "data =="+data # undefined
]

it will intercept the transformReq when use the POST method, I am looking for the way the deal with the req too.

Related

How to output json data in controller in angularjs

I am learning angularjs and i want to ouput some json data on console.
I am doing something like this
$scope.events = events.query();
but when i print on the console
console.log($scope.events);
it gives me the output like
Array []
how can i print the data like this
[
{"id":18,"file":{"url":"/uploads/playlist/file/18/01_-_MashAllah.mp3"},"event_id":23,"created_at":"2015-11-11T10:33:52.000Z","updated_at":"2015-11-11T10:33:52.000Z","name":"01 - MashAllah.mp3"},
{"id":19,"file":{"url":"/uploads/playlist/file/19/02_-_Laapata.mp3"},"event_id":19,"created_at":"2015-11-11T10:50:01.000Z","updated_at":"2015-11-11T10:50:01.000Z","name":"02 - Laapata.mp3"}
]
below is my whole code
.controller('ShowEventsCtrl', ['$scope','events', function($scope,events) {
$scope.events = events.query();
console.log($scope.events);
}]);
services
angular.module('myApp')
.factory('events', ['$resource',function($resource) {
return $resource('/events', {},{
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
})
}])
and when i print the data in html like this
<div ng-repeat="playlist in playlists">
{{playlist}}
</div>
I get the correct output so i but how to output it in console.
Because your events.query() method is asynchronous, you need to log stuff after the action is resolved. Easiest way I can think of is
$scope.events = events.query(function(events) {
console.log(events);
});
From $resource
The action methods on the class object or instance object can be invoked with the following parameters:
HTTP GET "class" actions: Resource.action([parameters], [success], [error])
...
Success callback is called with (value, responseHeaders) arguments
I'm guessing your confusion comes from this feature of $resource
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.
You see the correct data in your template because once the data is returned from the server, a scope digest is triggered and your template is updated.

How to convert Angular $resource object to regular object without methods

I am starting to learn AngularJS $resource, and noticed the $resource object has a few methods (see below for examples) attached to my data downloaded from server. How do I remove these methods and convert the object to a regular (array) object?
__proto__: Resource $delete: function (params, success, error) {$get: function (params, success, error) {$query: function (params, success, error) {$remove: function (params, success, error) {$save: function (params, success, error) {constructor: function Resource(value) {toJSON: function () {__proto__: Object
For instance, I'm trying to send a POST request including some key value data using $resource.save, but these 'proto' items in the array is somehow causing the data to become "undefined" when passed to $.param(data) in the factory. I could do the same thing using $http with ease, but want to learn $resource. Thanks!
Inside a Controller
$scope.ok = function () {
$scope.entry = new calEntry();
$scope.entry.data = data // data is $resource object including _proto_ items
$scope.entry.$save( function(){
toaster.pop('success','Message','Update successfully completed.');
});
};
Factory
myApp.factory("calEntry",['$resource','$filter', function($resource, $filter) {
return $resource("/griddata/", {}, {
save: {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: function(data, headersGetter) {
return $.param(data); // data is undefined when it reaches here
}
}
});
}]);
Try the toJSON function, it will fetch the data and remove the extra properties.

Angular: How to access transformRequest data?

In my controller I have this code to make request to my factory:
UploadService.news.save
data: angular.toJson $scope.data
file: $scope.file[0]
, ( (response) ->
#$scope.alert = ''
alert response.data
)
This will go to my factory:
app.factory "UploadService", ["$resource", ($resource) ->
news: $resource("upload/news",
headers:
'Content-Type': false
transformRequest: (data) ->
fd = new FormData()
fd.append 'data', data.data
fd.append 'file', data.file
fd
)
member: $resource("404/upload/member")
]
Problem is at transformRequest the data parameter is undefined, what is wrong with that? (I'm using Angular 1.2.3)
The way you declare your resource has several errors:
The $resource second argument is an hashmap for default parameter values
The third parameter contains actions (ie methods) for this resource. If you want to override the save action, you need to give its name.
Here is a working jsFiddle (Open your dev console, and then run)
app.factory "UploadService", ["$resource", ($resource) ->
news: $resource("upload/news", {}, # the missing second parameter
save: # You want to override the save action
method: 'POST' # it's an override, not an extend: need to set the method
headers:
'Content-Type': false
transformRequest: (data) ->
console.log data # data is now defined
return
)
member: ...
]
Or see the official doc

Passing a path with '/' to $resource or $http factory

Is there a way to pass a parameter containing / to Factory? Want to accomplish something like
.factory('MyData', ['$resource', function ($resource) {
return $resource('http://1.2.3.4/:urlFragment', {
urlFragment : '' // default empty
}, {
getData : {
method : 'GET'
},
And calling it
$scope.scopeVar = MyData.getData({urlFragment : '/some/path/to/data'});
Looking at the network console, I see that / are replaced with %2.
Can I encode the passed parameter inside Factory? (Using $http or $resource).
Or in general, how can I execute any functions on parameters inside factory?
No, you can't really get access to the url inside of your factory because $resource automatically handles it. But thankfully Angular gives you a way to get access to the url before it is called by using the $resource directly. Looking at the docs here, one of the actions you can supply in your $resource declaration is a transformRequest property.
return $resource('http://1.2.3.4/:urlFragment', {urlFragment: ''}, {
getData: {method: 'GET', transformRequest: function(data, headers){
// make your modifications here to either data or headers
}}
});
Although I haven't actually run this code, I believe that should allow you to do what you want. Let me know if it doesn't.

Delete headers from Angular.js $http request

I want to delete some $http request header fields from one specific request (it means not on the $httpProvider level). These fields are:
Cache-Control
If-Modified-Since
Referer
X-Requested-With
How to do this in a single request? I tried to use transformRequest parameter, but didn't find enough information to make it work. Such a [CoffeeScript] code:
$scope.logout = ->
$http({
method: 'GET'
url: '/api/logout'
headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' }
transformRequest: (data, headersGetter) ->
console.log data
console.log headersGetter
data
}).success ->
$location.path('editor')
shows that data is undefined, headersGetter is function (c){a||(a=Nb(b));return c?a[y(c)]||null:a} (which says to me absolutely nothing), and I didn't understand what to return from the transformRequest function.
If you use the unminified version of Angular, you'll get nicer backtraces when an exception happens, and you'll have an easier time introspecting the angular code. I personally recommend it while developing. Here's what headersGetter actually looks like:
function (name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
}
The data argument to your transformer will be undefined unless you’re POSTing some data.
The headersGetter function takes an optional argument name, if you want to get a single header, but you omit the argument to set a header:
headersGetter()['Cache-Control'] = 'no-cache';
headersGetter()['X-Requested-With'] = '';
The return value from your transformer should be the value of data you want to use.
You can’t change the Referer header from XHR.

Resources