Pass params to $httpBackend - angularjs

I'm trying to mock a $http get request with parameters. Using the actual $http service we could do something like this
$http.get(url, {params : { articleId:10, id : 1}})
.success(function (response) {
defer.resolve(response.data);
});
Can we do the same with $httpBacked?
$httpBackend.when('GET', url, { params: { articleId: 10, id : 1}})
.respond({data: areas});
The obvious unpleasant alternative is writing out the full expected url which I am hoping I don't have to do as this feels neater.
Thanks

I had forgotten about this question, unfortunately the answer is that you have to specify the full get url with parameters
....just incase someone stumbles across this with the same problem

Apparently the only thing that can be passed parameters in a regular expression. According to the documentation of angular only four parameters can be passed, method, url, data, and headers.

Related

Angular $resource get method not working

I have a simple resource like.
angular.module('app').factory('nmCategory', function($resource){
var categoryResource = $resource('/api/categories/:id',{id:"#id"}, {
update: {method: 'PUT', isArray : false},
get: {method: 'GET' },
});
return categoryResource;
});
When I called nmCategory.query(), i get all the result returned. However, i am trying to filter by id. Thats to the a single record ehre id is #id. I then try nmCategory.get({id: 1}); and to my surprise, it fails and returning
/api/categories/1 Not found (404)
I was expecting to get my single record my id . I searched through more examples online, yet none refute what i am doing. Please how do i achieve this? Any help would be appreciated.
Navigate to that URL in your browser and see if it works. It probably doesn't. This is most likely a back-end issue, not an Angular issue.

Set path parameter without affecting payload using $resource

First of all I want to mention that I have been digging around a lot for this. I am unable to find a simple and straight forward answer even in the docs. (Call me dumb if you will, in case it IS mentioned in the docs! I can't seem to find it anyway.)
The thing is, I want to make a PUT request to a URL of the form
app.constant('URL_REL_VENDOR_PRODUCTS', '/api/vendor/:vendorId/products/:productId');
But I do not want to put the vendorId parameter in the request payload. My service layer looks something like this:
services.factory('VendorProductService', function($resource, UserAccountService, URL_BASE, URL_REL_VENDOR_PRODUCTS) {
return $resource(URL_BASE + URL_REL_VENDOR_PRODUCTS, {
vendorId: UserAccountService.getUser().vendorId,
id: '#id'
}, {
update: { method: 'PUT' }
});
});
I know that instead of the vendorId: UserAccountService.getUser().vendorId I could have written something along the lines vendorId: '#vendorId' but then that pollutes my payload doesn't it?
I don't want to keep the mechanism I am already using in the example as the mechanism does not work when you switch accounts i.e.,if the UserAccountService.getUser() is updated. Basically I'm having to reload the entire page to get the service initialized again.
In short, the question is, as the title suggests, how do I set the path parameter vendorId without using a service like the one in the snippet and also without modifying the payload?
Make the parameter value a function:
services.factory('VendorProductService', function($resource, UserAccountService, URL_BASE, URL_REL_VENDOR_PRODUCTS) {
return $resource(URL_BASE + URL_REL_VENDOR_PRODUCTS, {
vendorId: function () {
return UserAccountService.getUser().vendorId
},
id: '#id'
}, {
update: { method: 'PUT' }
});
});
From the Docs:
paramDefaults (optional)
Default values for url parameters. These can be overridden in actions methods. If a parameter value is a function, it will be executed every time when a param value needs to be obtained for a request (unless the param was overridden).
-- AngularJS $resource API Reference

Two methods to make HTTP post call in AngularJS , which one better to use?

Is there any good reason why should I use this type of $http post method:
$http.post("http://localhost:53263/api/Products/",$scope.product).
then(function (data) { alert("success") }, function (data) { alert("error") });
over this method:
$http({method: 'POST',
url: 'http://localhost:53263/api/Products/',
data: $scope.product
});
So my question is which one is better to use? And for what purpose?
If you are asking purely between $http() (where you have to specify POST as a parameter) vs. $http.post() - then it's a matter of preference. The $http.post is meant as a shortcut (and equivalent) to $http() with the parameters you listed.
If you are asking about the promise aspect, both of these call will return a promise. So no matter which approach you decide to take, you can continue to append a success and error callback.
So if you use $http.post(...), you would utilize the callbacks like:
$http.post(...).success(mySuccessFn).error(myErrorFn);
Hope this helps!

Extracting cookies from $resource

This seems like it should be dead simple. I want to use $resource to save() something to the server. The server will respond with a cookie. I need to use that cookie on my next request. Somehow, in the year 2014, it seems that this is literally impossible.
The $resource looks something like this:
cartService.factory('AddToCart', ['$resource', function($resource) {
return $resource('my-url.com'
{
withCredentials: true,
transformResponse: function(data, headersGetter) {
alert(headersGetter);
}
}
);
}]);
First of all, the transformResponse isn't firing at all. I figured I might be able to breakpoint it and look at the backing object... nope.
Second, the only header there seems to be the content-type header. Everything from Date to X-* to transfer-encoding seems to be stripped out.
If I add a success() function to the call, it looks like this:
$scope.order = AddToCart.save({}, function(a, b) {
console.log(a);
console.log(b('JSESSIONID'));
});
Again, nothing. I'd really appreciate any pointers. If I have to dig into the $http guts just to deal with cookies, I can't help but be confused by the point of this framework.

AngularJS TypeError: Cannot read property 'protocol' of undefined

I have changed the $http > URL parameter inside my AngularJS app from
$http({ method:'POST',
url:'http://localhost/api/clients.php'
}).success(function(data,status,headers,config){
deferred.resolve(data);
}).error(function(data,status,headers,config){
deferred.reject(status);
});
to
$http({ method:'POST',
url: ConfigService.Urls.Clients
}).success(function(data,status,headers,config){
deferred.resolve(data);
}).error(function(data,status,headers,config){
deferred.reject(status);
});
where ConfigService is as follows:
Urls: {},
loadUrls: function(){
Urls.Clients = 'http://localhost/api/clients.php';
}
Of course I call loadUrls before loading controller through .Resolve so I am 100% sure Urls.Clients is not null.
After I did this change I started getting error:
TypeError: Cannot read property 'protocol' of undefined
at urlIsSameOrigin (http://localhost/myapp/app/lib/angular/angular.js:13710:17)
at $http (http://localhost/myapp/app/lib/angular/angular.js:7508:23)
What is so confusing is that the application works just fine, except for that error I am getting...can someone please tell me what I am doing wrong here? and why I am getting this error if the application is already working without a problem.
This is clearly an issue with order. The loadUrls isn't getting called until after the $http call is run for the first time. This could be because controllers aren't necessarily loaded in the order you expect - you can't count on the route provider opening and starting up your home controller before it runs other controllers - that is just going to depend on how things are setup. Given the amount of code you have provided here its hard to say what exactly is going wrong as far as order.
That in mind you have a few general options that will fix this:
Always call loadUrls() before you run a $http request. This isn't elegant but it will fix the issue
Wrap all of your $http calls and call loadUrls() in that wrapper. This is slightly better than the previous because if you need to change loadUrls() or make sure it is called only once you can implement that logic later.
You already observed this, but you can change your initialization to be directly in the service rather than in a routine provided by the service. This will fix the issue although it may leave you in a place where you have to update the service every time the url's change.
Live with the error, knowing that when the controller loads it will instantiate and get the correct data at that point in time. I don't often love solutions like this because it could cause errors later that are hard to trace but if you don't like any of the previous options this could technically be ok.
Use an app configuration, which is executed when the application loads (note that not all resources are initialized and injection is not allowed). An example from the documentation:
angular.module('myModule', []).
config(function(injectables) {
// provider-injector
// This is an example of config block.
// You can have as many of these as you want.
// You can only inject Providers (not instances)
// into config blocks.
}).
You can use this or a run block to initialize what you want
I'm sure there are other options as well depending on how your code is structured but hopefully this at least gets you started. Best of luck!
I had this same problem, and I fixed it by changing this:
var logoutURL = URL + '/logout';
function sendLogoutHttp(){
return $http({
method: 'GET',
url: logoutURL,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
to this
function sendLogoutHttp(){
var logoutURL = URL + '/logout';
return $http({
method: 'GET',
url: logoutURL,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}

Resources