Angular js- Setting headers in a ngResource - javascript

I am trying to set some customer headers in a service factory. Here is the code:
angular.module('clinicalApp').factory('encounterService', function ($resource) {
var EncounterService = $resource('http://localhost:port/v1/providers/:providerId', {providerId:'#id', port: ':8280'}, {
search: {
method: 'GET',
isArray: true,
headers: {
'RemoteUser': 'billybob'
}
}
});
return EncounterService;
});
Here is the code that calls the service.
angular.module('clinicalApp').controller('MainCtrl', function ($scope, encounterService) {
encounterService.search({
limit: 2000,
organizationId : '11110000'
});
});
When I use this resource and everything works fine, but the header is not set on the ajax call, so I get a 401 in return. What else do I have to do to set the headers? Thanks for the help.

I am sure the other answers I received work, but I did not want to use $http, I wanted to use $resource. To use resource with custom headers, I had to upgrade my Angular version. I did not look into the source code to find the reason why, and I don't know what version this functionality changed. Right now I am using v1.2.0-rc.2 and everything just worked. It took a few changed in the app config, namely I had to name ngRoute as a dependency to make the version work, but then I was able to use $resource like we are supposed to do.

Don't use run(), use config() with $httpProvider:
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common = {
'RemoteUser': 'billybob'
};
}])

clinicalApp.run(function($http) {
$http.defaults.headers.common["Content-Type"] = "application/json, charset=UTF-8";
});

Related

Send file based dummy data from Angularjs REST resource

I am trying to let UI development proceed without needing to be coupled to a backend. My the normal REST api is being built like:
a.factory('Sample', ['$resource',
function($resource){
return $resource(baseUrl() + '/sample/:id', {}, {
query: {method:'GET', params:{id:''}, isArray:true, cache:false},
update: { method:'PUT' },
remove: { method:'DELETE'}
});
}]);
This is fine when there is an actual backend. However, for development purposes (NOT Testing), canned data from a file is desired. This can be achieved like:
['$scope', '$http',
function($scope, $http) {
$http.get('data/sampleList.json').success(function(data) {
$scope.sampleData = data;
});
}]
Obviously, I'm no expert here, but I am wondering if there is an easy way to combine these two approaches such that the $resource REST instance can return (for GET requests anyway), canned data from a file?
Why didn't you say this was such a newb question or that you never RTFM? Oh wait, this is my own question! So, sorry folks, didn't realize this was quite so trivial - there is a 'URL' parameter available on every such method. While this will only work for Mockups or UI dev before the backend is done, for the above, all I needed to do was:
a.factory('Sample', ['$resource',
function($resource){
return $resource(baseUrl() + '/sample/:id', {}, {
query: {url: 'data/sampleList.json', method:'GET', params:{id:''}, isArray:true, cache:false},
update: { method:'PUT' },
remove: { method:'DELETE'}
});
}]);
qed

Angular JS and Cross Origin Requests

I am just playing around with angular JS and wiring it up to some restful web services I have implemented. I have moved onto using the $resource module provided by angular and have a simple question (I hope). In my code below I am making a request to a spring boot micro service I have written and am wanting to know the best way of accessing the URL.
So is there another way of calling the resource that is cross origin rather than having to write the line below. Is there something like /customer/greeting I could use but then how would I specify the different port as my angular app resides on localhost:8000?
http://localhost\:9001/customer/greeting //this is a spring boot application
My full code for the service.js is below this resides on localhost:8000 and is a node JS server.
'use strict';
/* Services */
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
phonecatServices.factory('Phone', ['$resource',
function($resource) {
return {
pDetail: $resource('phones/:phoneId.json', {}, {
query: {method: 'GET', params: {phoneId: 'phones'}, isArray: true}
}),
cDetail: $resource('http://localhost\:9001/customer/greeting', {}, {
query: {method: 'GET'}
})
};
}]);
When people normally implement do they have lots of http://balh blah when it goes cross origin? Is there a pattern that can be applied here?
Thanks in advance.
You can do this way:
Make function
var getCrossOriginUrl=function(portNo){
var crossOriginPath="http://localhost\:"
return crossOriginPath+portNo+"/";
}
So now you can call this way:
$resource(getCrossOriginUrl(9001)+'customer/greeting',{}, {
query: {method: 'GET'}
})

How to inject services to monitor authentication and storage status?

I'm using Angular.js to build a client side application with Restangular.
The problem is, I implemented a digest authentication with a wsse header which i have to generate at each request to my REST Server.
I saw that Restangular provide a function : addFullRequestInterceptor().
So now, i'm trying to use it inside my RestangularProvider to configure it in this file restangular.js :
// Config Restangular
app.config(function(RestangularProvider) {
RestangularProvider.setBaseUrl(applicationConfig.SERVER_URL);
RestangularProvider.setDefaultHeaders({'Content-Type': 'application/json'});
RestangularProvider.addFullRequestInterceptor(
function (element, operation, route, url, headers, params, httpConfig) {
// Here is my header generation.
$http.defaults.headers.common['X-WSSE'] =
TokenHandler.getCredentials(
AuthHandler.authentication.user.username,
AuthHandler.authentication.secret);
return {
element: element,
headers: headers,
params: params,
httpConfig: httpConfig
};
});
});
But i have an injection problem and i can't find out how to inject my TokenHandler service & my AuthHandler service to be able to know if the user is already loggedin or not and if he has localstroage or not.
Thanks for the help ;)
The problem is that in the .config phase the services, like AuthHandler and TokenHandler are not yet instantiated, so you need to instantiate them (and their dependencies) manually with $injector (which is injectable into config blocks):
app.config(function(RestangularProvider,
$injector,
AuthHandlerProvider,
TokenHandlerProvider) {
var AuthHandler = $injector.instantiate(AuthHandlerProvider.$get);
var TokenHandler = $injector.instantiate(TokenHandlerProvider.$get);
//...
});

How to cache http in Angular until parameters changed?

Is it possible to cache some http until parameters used in url change:
app.factory('dataService', function ($http,$rootScope) {
return {
getData: function () {
return $http.get(rest.getData
+ $rootScope.number + "/" + $rootScope.blb
).then(function (result) {
return result.data;
});
}
}
});
So, when $rootScope.number changes in controller, I need to call http again, until then it should be cached. Is it possible and how?
Angular's $http has cache built in. Set cache as true in your $http request options:
$http.get(url, {cache: true}).then(...);
If you want to cache data you can do it in a number of ways.
You can cache it inside your service also.
Here is post which should help you.

Angular & Twitter REST API

I've been hunting for a few hours now and can't seem to find any information specific to my setup so here goes.
I'm using the MEAN stack and wanting to use the Twitter API in my angular app. I have all the required keys and trigger a twitter api authentication on the server side using Node, then pass the token I get in response to my angular pages. I was hoping to be able to use this token to make requests to the api from an angular service. The request I'm trying to get working the moment is to fetch a given user's profile object. I've attached my service method below. The error I get when I run it is a 405 method no allowed, no access-control-allow-origin header is present.
angular.module('tms.system').factory('Twitter', ['$log', '$q', '$http', '$window', 'twitter', 'Global', function($log, $q, $http, $window, twitter, Global) {
return {
findProfile: function(handle) {
var deferred = $q.defer();
var config = {
timeout:3000,
headers: {
'Authorization': 'Bearer ' + Global.twitterToken,
'X-Testing' : 'testing'
}
};
$http.get('https://api.twitter.com/1.1/users/show.json?screen_name=' + handle, config).
success(function(data) {
$log.info(data);
deferred.resolve(data);
}).
error(function(status) {
$log.error(status);
});
return deferred.promise;
}
};
}]);
Just for future reference, as stated in the comments of maurycy's answer {and being myself trying to get tweets just from Angular without succes}, the best approach for this would be to get them from some backend.
I believe you should use $http.jsonp with a JSON_CALLBACK to get it to work, it's not going to happen with $http.get for sure

Categories