Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i change Accept-Language Request Header with AngularJS

Is there a way to change or edit the accept Language header that i send to my API ? is there a way in javascript Jquery or Angular? i don't want to send the default one, but the one my Cookie has!

like image 997
Almin Islamovic Avatar asked May 13 '15 13:05

Almin Islamovic


People also ask

How do I change my language header?

The user can change the Accept-Language header sent by the browser using the browser's preference settings. E.g., in Chrome, go to “Settings”, click on “Show advanced settings...”, scroll down to “Languages”, click on “Language and input settings...”, and then add languages and drag to order them.


2 Answers

In AngularJS you can set common headers by using $httpProvider and you can get the cookies by using $cookies service.

For example:

var app = angular.module("app", []);

app.config(["$httpProvider", "$cookies", function($httpProvider, $cookies) {
    // set Accept-Language header on all requests to
    // value of AcceptLanguageCookie cookie
    $httpProvider.defaults.headers.common["Accept-Language"] = $cookies.get("AcceptLanguageCookie");

    // or set headers on GET requests only
    if (!($httpProvider.defaults.headers).get) {
        ($httpProvider.defaults.headers).get = {};
    }
    $httpProvider.defaults.headers.get["Test-Header"] = "value";
}]);
like image 174
gaiazov Avatar answered Sep 18 '22 02:09

gaiazov


To reference the cookie which contains your specific "Accept-Language" value you will want to do this at run time. The reason is that the app config only accepts Providers and the reference to Services is not recommended.

To do this at run time you will want to make use of the $http and $cookies services

Here's an example:

var app = angular.module("app", []);

app.run(["$http", "$cookies", function($http, $cookies){
  // set Accept-Language header on all requests
  $http.defaults.headers.common["Accept-Language"] = $cookies.get("LocaleCookie");
}]);

To statically set the "Accept-Language" WITHOUT a cookie then you can use .config()

var app = angular.module("app", []);

app.config(["$httpProvider", function($httpProvider) {
  // set Accept-Language header on all requests
  $httpProvider.defaults.headers.common["Accept-Language"] = "fr";
}]);
like image 21
Kevin B Avatar answered Sep 20 '22 02:09

Kevin B