Gettting the received Http Headers in Angular JS ui-router - angularjs

I am a newbie for Angular.
I am having the following Angular JS(v.1.7) ui-router
.state('helpPage', {
url: "/help",
data: {
roles: []
},
views: {
helpDoc: {
templateUrl: 'app/modules/help/help.tpl.html',
controller: 'helpCtrl'
}
}
})
When the User hits this page I want to retrieve the Headers.
Can I get them in the Controller or in the ui-route's resolve method itself ?
Tried HttpInterceptor but it is not helping out.
Any help is much appreciated.

Use the headers property of the $http response object:
$http.head(url).then(function(response) {
var headerGetter = response.headers;
console.log(headerGetter("headerName"));
});
For more information, see
AngularJS $http Service API Reference - $http.head

Related

Get "initially loaded" (not AJAX call) Response Headers with AngularJS

In looking at How to read response headers in angularjs?, I see answers that involve making an http/ajax request after the page loads then getting the response headers.
I have an angularJS app that needs to render the page (immediately when it loads, not after) using some JSON in a custom response header key that I've added on my python backend.
Is there non-hacky a way to do this? Or is the very attempt at rendering a web page using AngularJS to parse response headers a hack in itself?
My headers look like this (I'm trying to get myjson) :
Keep-Alive:timeout=1, max=100
myjson:{"key2": "value2", "key1": "value1"}
Server:Apache
I think this is what you are aiming for, using $http and ngRoute. Forgive me if I'm misunderstanding. It's just loading data about this question via SO's API. If you click Load Data, you'll see the headers from SO on that page..
var app = angular.module('plunker',['ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/home', {
template: '<h1>Test 1</h1>',
controller: 'HomeCtrl'
}).
when('/loaddata', {
templateUrl: 'load_data.html',
controller: 'LoadDataCtrl',
resolve: {
stackQuestion: function($http){
// We must return something with a promise. $http already does that, so does $resource.
// See: https://docs.angularjs.org/api/ng/service/$q
return $http({
method: 'GET',
url: 'https://api.stackexchange.com/2.2/questions/37491743?order=desc&sort=activity&site=stackoverflow'
})
}
}
}).
otherwise({
redirectTo: '/home'
})
}
]);
Then, in your controller:
app.controller('LoadDataCtrl',function(stackQuestion,$scope){
// now our data is here
$scope.question = stackQuestion.data;
$scope.headers = stackQuestion.headers();
});
http://plnkr.co/edit/ylOfSNqPAqjdg9rYxsbb?p=preview

How to create a POST request in my case?

I am trying to make a POST request via $resource object in Angular.
I have something like
(function (angular) {
angular.module('myApp')
.factory('myService', [
'$resource',
function ($resource) {
var serviceObj = $resource('http://testProject/products/', {id: '#id'},{
'createItem' : {
url: 'http://testProject/item/:id',
method: 'POST',
params: {type: ‘#type'}
}
});
return serviceObj;
}
]);
})(angular);
in my controller
//omit the controller codes…
myService.type = ‘Detail’;
myService.createItem(function(data) {
console.log(data)
});
I see stuff back from the console.log but it has the wrong data because the type is shown as ‘Name’ instead of ‘Detail’. I know api supports that and I don’t see anything wrong with my service. Can someone help me out for it? Thanks a lot!
It looks like your are getting data back,
I would try:
console.log(data.data);
Since your are returning an object from your service.

AngularJs $resource, REST and Symfony2 FOSRestBundle

I am using the FOSRestBundle, this bundle generates routes for me and pluralises those routes. For instance a GET request to /users.json is different from a GET request to /user/15.json
Its worth noting that a call to /users/15.json fails.
More on this issue here https://github.com/FriendsOfSymfony/FOSRestBundle/issues/247
In my Angular app I use a $resource to create a RESTful call, the URL is a template as detailed here https://docs.angularjs.org/api/ngResource/service/$resource
For example
$resource('http://example.com/:id.json')
Or
$resource('http://example.com/user/:id.json')
And there in is the problem, the $resource seems to accept a single URL template for the REST resource, but I have multiple ones because of the forced pluralisation from the FOSRestBundle.
I do not think hacking the FOSRestBundle is the answer, so what can I do with my usage of $resource in AngularJs to correct this issue?
you can set url for every method as third parameter - actions
angular.module("example", ["ngResource"])
.factory("userService", function($resource) {
return $resource("http://example.com/user/:id.json", {
id: "#id"
}, {
'query': {
url: "http://example.com/users"
}
})
})
.run(function(userService) {
userService.query();
userService.get({id:1});
})

How to add translations to $translateProvider from outside the config?

I am new to angular js. For language translation I am using angular-translate service in my work.I am getting the entire translations which I need to assign in $translateProvider by an API call response.I know that I can assign the translations to $translateprovider ($translateprovider.translations ('en',translations) only from config module but I think that an API call from config module is not a good practise.
Below given is my config module.
.config(['$translateProvider', function($translateProvider) {
//fetching session key
var response;
jQuery.ajax({
type: "GET",
url: 'https://abcdefg/session?appKey=123456',
async: false,
success: function(data) {
response = data;
getMetaData(response.sessionKey);
}
});
////fetching data.
function getMetaData(sessionKey) {
jQuery.ajax({
type: "GET",
url: 'https://abcdefg/metadata?sessionKey=' + sessionKey +
'&gid=1.2.3.4',
async: false,
success: function(data) {
dataSet = data; //save response in rootscope variable
}
});
}
$translateProvider.translations('en_US', JSON.parse(dataSet.en_us));
$translateProvider.translations('es_ES', JSON.parse(dataSet.es_es));
$translateProvider.preferredLanguage('en_US');
}
How can this be solved? How can I assign translations to $translateProvider from out side the config module?
Thanks in advance.
Take a look at this answer from the creator of angular-translate, where he states that "[...]there's no way to extend existing translations during runtime with $translate service without using asynchronous loading.[...]"
For more information on asynchronous loading of translations take a look at the documentation. You may even specify your own custom loader to get translations by calling your API.
By many purposes, we may need to add more translations in Services, so I found a way to do that.
We can create another CustomProvider which returns $translateProvider, and then we can inject CustomProvider to Services or Controllers.
// NOTE: Create another Provider returns $translateProvider
.provider('CustomProvider', function($translateProvider) {
this.$get = function() {
return $translateProvider;
};
});
// NOTE: Inject CustomProvider to Service to use
.factory('TranslationService', function(CustomProvider) {
console.log(CustomProvider);
return {
addMoreTranslations: addMoreTranslations
};
function addMoreTranslations(key, translations) {
// Do somethings
CustomProvider.translations(key, translations);
}
});
I succeeded by that way.

Angularjs Params

I'm new to Angular. I'm trying to post a tag under a BlogPost.
Here's what I started with (Angularjs Service):
angular.module('app.tags').factory("Tags", ['$resource', function($resource) {
return $resource('posts/:postID/tags/:tagId', {
tagId: '#_id',
postID: // Post ID?
}, {
update: {
method: 'PUT'
}
});
}]);
How would I get the postID to match up with my Post's ID?
Documented with $route service the current.params object holds all of the current route parameters.
$route.current.params
So, you can address postId by injecting $route and asking for:
$route.current.params.postId

Resources