1

I want to send headers each time for CRUD operation from factory side. Here is my factory

var appangular.module("LifeStyleFactModule",["ngResource"]);
 app.constant("RES_URL", "http://localhost:9090/")
app.factory("CategoryFactory",function($resource,RES_URL){
var categoryinfo;
var categoryresource=$resource(RES_URL+"category/:id",{"id":"@id"},{update:{method:"PUT"}});
return{
    getcategory:function(){
        categoryinfo=categoryresource.query();
        return categoryinfo;
    },
     addcategoryItem:function(categoryItem){

        var category = new categoryresource(categoryItem);
        category.$save(function(respdata){

            categoryinfo.push(respdata);

        },function(respdata){
        });
    },
    deletecategoryItem:function(idx,id){
        var category=new categoryresource({"id":id});
        category.$delete(function(){
            categoryinfo.splice(idx,1);
        },function(){
        })
    },
    updatecategoryItem:function(categoryItem,idx){
        var category=new categoryresource(categoryItem);
        category.$update({"id":categoryItem._id},function(data){
             categoryinfo[idx]=data;
        },function(){
        })
    }
}
})

the above functionality is working well. Now i want to send the token in the headers. How can i do that.

I have tried to do it by the following way

var categoryresource=$resource(RES_URL+"category/:id",{"id":"@id"},{update:{method:"PUT"},headers:{"token":"@token}});

but not getting how to send the token for CRUD operation.

Is procedure is correct, if so how can i send tokens.

Else let me know the way.

Instead of above method i tried the following way as

 $resource(RES_URL+"category",{},{query:{method:"get",isArray:true,headers:{"token":token}}}).query({},function(res){});

this is working but the procedure for the first procedure.

Please after answering mark it as duplicate or down vote

dont say ( / { such things are missing.

Abhishek
  • 1,477
  • 1
  • 10
  • 18
ANK
  • 293
  • 2
  • 10

1 Answers1

0

The best solution as to me is to use interceptor. Here is a way to send token in headers, I've used in one of my projects.

angular
  .module('app.core')
  .config(config);

config.$inject = ['$httpProvider'];

function config($httpProvider) {
  $httpProvider.interceptors.push(interceptor);
}

interceptor.$inject = ['$q', '$injector', 'AuthModel'];

function interceptor($q, $injector, AuthModel) {
  return {
    request: function (config) {
      config.headers.Authorization = AuthModel.token;
      return config;
    },
    responseError: function (rejection) {

    }
  };

}

Added a jsfiddle to demonstrate

https://jsfiddle.net/Sergey_Mell/c47js1zc/

Just click the Send button and check the request headers in developer tools

Sergey Mell
  • 7,780
  • 1
  • 26
  • 50