The $resources headers have not been updated

My objective is to include a header with each HTTP request for an ngResource (specifically, an auth token).

This solution somewhat accomplishes that:

app.factory('User', ['$resource','$window',
  function($resource,$window,liftHost, liftBasePath) {

     return $resource('/api/users/:id',{},{ 
      get: {
               method: 'GET',
               headers: {'token': $window.sessionStorage.token}
          }

     });
  }]);

The issue with this code is that after the initial call, subsequent GET requests will have the same header value. The header does not get updated dynamically. So, if a user logs out and then logs back in, changing the value of $window.sessionStorage.token, the request will still use the old token.

I have put together a small plunker using $httpBackend mocks to demonstrate this problem.

Check it out here: http://plnkr.co/edit/xYZM6wlDJ6CH2BPHLZAC?p=preview

Answer №1

Check out this code sample on how to implement TokenService in AngularJS.

I created a TokenService that is injected into the User and Session services, making the code cleaner without relying on the $window service. Additionally, I changed the token from a primitive string to an object for passing by reference rather than value.

app.factory('Token', [
  function() {
    return {
      value: "xyz"
    }
  }
]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the value of an object from a string and make a comparison

var siteList = {}; var siteInfo = []; var part_str = '[{"part":"00000PD","partSupplier":"DELL"}]'; var part = part_str.substring(1,part_str.length-1); eval('var partobj='+part ); console.log(par ...

React is unable to identify the `InputProps` prop when applied to a DOM element

Caution: React is not able to identify the InputProps property on a DOM element. If you intend for it to be displayed in the DOM as a custom attribute, spell it in lowercase as inputprops. If you accidentally passed it from a parent component, remove it fr ...

React js code to create a position ranking table

Currently, I am in the process of developing a web application using Reactjs with a ranking table managed by Firebase. However, I have encountered a question: Is it possible to dynamically change the position numbers after sorting the table based on the am ...

What is the best way to incorporate correct reference logic when utilizing Joi validation?

I am currently working on designing a straightforward schema to validate inputted number ranges. The condition is that the start value should be less than the end value, and conversely, the end value must be greater than the start value. Below is the sche ...

Troubleshooting a CSS problem within mat-autocomplete component in Angular 7

While using mat-autocomplete, I noticed that when I select an option from the dropdown and then scroll through the main bar, the dropdown menu does not move along with the autocomplete input field. view image here Here is the code snippet: <td width ...

retrieving a map containing the values from an array using the `.includes()`

Currently, I am attempting to map my routes based on the roles they possess. For example, my mapped routes may have roles like ["User", "Admin"] or just ["Admin"]. The current user can have one or multiple roles assigned to them. This particular function w ...

After using browserify, when attempting to call the function in the browser, an Uncaught ReferenceError occurs

I am currently in the process of creating a compact NPM package. Here is a basic prototype: function bar() { return 'bar'; } module.exports = bar; This package is meant to be compatible with web browsers as well. To achieve this, I have inst ...

The post processing effect in Three.js does not support FXAA when SSAO is activated

I am having trouble getting SSAO and FXAA effects to work together in this simple test scene. Enabling SSAO works fine, but when I also enable FXAA, the render turns black. In the provided fiddle, if you uncomment composer.addPass(FXAA_effect); you will s ...

Differences in behavior of multiple select with track by in Angular versions above 1.4.x

I recently upgraded my product from Angular 1.2.x to 1.4.x. Since updating to angularjs 1.4.x, I've encountered an issue: What I have: I included code snippets for both angular 1.2.0 and 1.4.8. You can check out the comparison on JSFIDDLE. Explanat ...

Executing a click on a checkbox element in Python with Selenium

Background: Currently, I am in the process of developing a Python script that will automatically download listings from a specific website. I have successfully programmed the script to navigate the webpage, search for keywords, click on the search button, ...

Tips for creating a secure authentication system in an AngularJS application!

As a novice in the world of angularjs... After going through the documentation and completing a tutorial, I decided to experiment on my own which has helped me grasp things better. Now, I'm looking into creating a secure authentication system. The ...

Subsequent $http requests become trapped in a pending state and eventually fail with a NodeJS server

I encountered a strange issue with Angular and Node that I can't seem to find a solution for. In my Angular controller, I have a function that fetches data initially and stores it in $scope. This function also allows the controller to make a POST req ...

Locate the parent and child elements within an array

Within the array provided below, there are parent items as well as children. I am currently able to identify parents (depth 0) and their immediate children (depth 1), however I am unsure how to handle deeper nested levels. For reference, you can view the ...

The problem arises when the type of a Typescript literal union becomes more specific within React children

Currently, I am in the process of converting our React/Redux project to TypeScript and encountering a challenge with TypeScript literal type union types. The issue that I'm facing is as follows: I have instantiated a Wrapper component with a type pr ...

Implementing subgrids within ng-grid

I am new to angularjs and have a question about creating a sub grid inside another ng-grid. Is it possible? I want to have links in a column of the main grid, so that when a link is clicked, a new grid with 4 columns will be generated within the existing ...

What is the best way to reference a nested child property within a directive's scope?

Hello my beloved pals, We have the ability to connect a scope property of a directive to the value of a DOM attribute. Here is an example that demonstrates how it works: module.directive 'MyDirective', -> scope: directiveVar: '=& ...

Can you suggest a secure approach to implement `Object.assign` in AngularJS?

Is there a reliable way to perform Object.assign in order to create a copy of my data without any AngularJS properties attached, past, present, or future? I could manually delete specific properties like $$hashKey after assignment, but this method is frag ...

Error: Attempted to access keys from a non-object value. - Gruntfile.js

Can anyone help me resolve the following issue: Error Message: PhantomJS 1.9.8 (Windows 7) ExampleController should query the webservice FAILED Error: [$injector:modulerr] Failed to instantiate module TestWebApp due to: TypeError: Requeste ...

Extracting information from JSON structure

My JSON object response includes a `series` array of objects structured like this: { series: [ { name: 'a', data: [1,2,3] }, { name: 'b', data: [4,5,6] } ] } I am looking to extract the `data` values th ...

Is there a method by which I can access information from a linked document in Firebase?

I am relatively new to firebase and I am attempting to retrieve data from a referenced document in another collection to display. Link 1 Link 2 This is how I add a student and the parent's ID: const newStudent = { name: req.body.name, grade: ...