Niranjan Godbole Niranjan Godbole - 1 year ago 69
AngularJS Question

How to get data from factory and send it in headers?

Hi I am developing web application in angularjs. I am making lot of http calls to interact with web api. As a result i have to send lot of data in headers too. I have created factory for get data as below. These data should should be passed in headers. Below is my factory.

var myapp = angular.module('RoslpApp');

myapp.factory("ScrollFunction", ['$location', '$anchorScroll', '$cookieStore', function ($location, $anchorScroll, $cookieStore) {
return {
getheaders: function () {
var cookiePreferredLanguage = $cookieStore.get('PreferredLanguage');
var headers={
Logintoken: $cookieStore.get('LoginToken'),
LoginId: $cookieStore.get('LoginID'),
RequestedPlatform: "Web",
RequestedLanguage: cookiePreferredLanguage
return headers;

Below is my sample http call.

function getpermissiondetails() {
var headersdata = ScrollFunction.getheaders();
$scope.Create = "Create";
var getsavedvechilceUrl = baseurl + "api/RolesPermission/getgroups";
var request = {
url: getsavedvechilceUrl,
method: 'GET',
headers: {
RequestedPlatform: headersdata.RequestedPlatform,
RequestedLanguage: headersdata.RequestedLanguage,
Logintoken: headersdata.LoginToken,
LoginId: headersdata.LoginID
$http(request).then(function (response) {
$scope.groups =;
}, function (error) {

What i want in header is i already have data in var headersdata = ScrollFunction.getheaders(); Is it possible to pass something like headers: { headersdata } because i can make add headers in factory. No need to expand it in each http call. I tried headers: { headersdata } but this is not sending any data to api. May i know is there any better solution? Any help would be appreciated. Thank you.

Answer Source

I guess this is a code refractoring question.

Q: Can I avoid doing the messy property assignment by doing something shortcut like headers={ factory data }?

A: Ok. I probably did a bad job paraphrasing your question. I'm just trying to make it more understandable.

Short answer: Yes. You can further shorten your code by doing this.

var request = {
    url: getsavedvechilceUrl,
    method: 'GET',
    headers: ScrollFunction.getheaders()


Your function getheaders() is already returning a javascript object which is exactly what request.headers is looking. An object {}.

Since getHeaders() is already returning an object you can just plug it straight into request.headers. That is, you no need to re-create an object and reassign the property back in one by one.

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download