Using AngularJS to maintain a 'Token' throughout the duration of the application

Currently utilizing AngularJS with Restangular to authenticate a user during the login process. Once authenticated, a 'Token' is returned which must be utilized for all subsequent requests.

My inquiry pertains to the optimal method of storing this token using AngularJS. It is crucial that the token persists throughout the lifetime of the application.

I have considered utilizing services for this purpose, but I am encountering the need to repeatedly inject it into controllers in order to maintain its presence.

Answer №1

Life is unpredictable when it comes to using web apps, but there is a solution - utilizing localstorage. Here's a sample service demonstrating how to leverage localstorage in Angular. Simply add the following code to your service.js file:

var storeService = innovidServices.factory('storeService', function() {

    var service =
    {
        setClientData:function(client_details)
        {
            window.localStorage.setItem( "client_data", JSON.stringify(client_details) );
            client_data = client_details;
        },
        getClientData:function()
        {
            if (client_data == null)
            {
                client_data = JSON.parse(window.localStorage.getItem("client_data"));
            }
            return client_data;
        }
    }

    var client_data = null;

    return service;
});

Answer №2

Storing the 'Token' in the $rootScope seems to be the most effective approach.

myapp.controller('loginCtrl', function($scope, $rootScope) {
    ...
    $rootScope.token = Token;
    ...
});

An alternative method is to utilize an http interceptor to add this token as a GET parameter to every query.

myapp.factory('httpTokenInterceptor', function ($rootScope) {
  return {
    request: function (config) {
      var token = $rootScope.token;
      if (token) {
          config.url =  URI(config.url).addSearch({'token':token}).toString();
      }
      return config;
    }
  };
});

myapp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('httpTokenInterceptor');
});

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

Ways to serve JSON response following a 400 error code

After a user submits incorrect form details, such as an invalid username or blank email address, I make an Ajax request to my REST API. The response data I receive is structured as follows: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: applicati ...

What is the best way to dynamically shift the position of an image on a page while keeping it in place in real-time?

A group of friends and I are currently collaborating on an experimental project for a presentation. Our goal is to have multiple elements (such as images, text, gifs) displayed on a page that can be dragged around in real-time using a draggable script whi ...

Struggling to navigate to a specific div element using a hash in an Angular application

I came across some information here and here stating that a page can be scrolled to a specific element using just a hash selector and an id attribute. However, I am facing difficulties implementing this in my Angular application. Could this be because of ...

Prevent altering client values via developer tools

Our application is built using HTML5, the Foundation framework by ZURB, and AngularJS. We are seeking a way to prevent users from accessing and changing the values of our Angular objects (specifically scope variables) through the developer tool console. ...

Retrieve the properties of an object

I have a JavaScript program where I retrieve values from a JSON file and store them in an array. However, when I attempt to access the elements of this array, it returns nothing. Below is the function that pushes temperatures: temperatures = [] get_info ...

Calculate the total value of a certain field within an array when a specific condition is satisfied

I have two sets of data. I am looking to calculate the total time_spent for each course_id that appears in both set 1 and set 2. let set1 = [ { instructor_id: 7, course_id: 19, lesson_id: 1, time_spent: 0 }, { instructor_id: 7, course_id: 19, lesson_ ...

Troublesome CSS Zoom causing issues with jQuery scrollTop

As I design a website that has a fixed width and zooms out on mobile browsers, I've opted to adjust the zoom using CSS rather than viewport meta tags: html, body { zoom: 0.8; } It's been effective so far, but now I'm facing an issue wi ...

A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation: interface Time { hours: number; minutes: numbe ...

The Simple HTML Dom parser is failing to parse contents on these specific websites

I tried using a basic HTML DOM parser but it's encountering issues when parsing certain websites. include_once 'simple_html_dom.php'; $html=file_get_html('http://www.lapenderiedechloe.com/'); This results in an error message like ...

Troubleshooting the Create Order Issue: Integrating PayPal Checkout with Smart Payment Buttons using React and Redux

Every time I attempt to process a payment, I encounter a 422 error: Unprocessable entity. The issue arises when I try to dynamically capture the purchased item details received from the redux store. I tried following this example (duplicate): PayPal Check ...

Node.JS encountered an issue preventing the variable from being saved

I've been attempting to store the request.headers, but every time it outputs as [object Object] in the txt file. var http = require("http"); url = require("url"); fs = require("fs"); var events = require('events'); var even = new events.Ev ...

The output in the window will display the result of doubling the input box value, not the div

Can someone help me figure out why my code isn't working as expected? I'm trying to create a text box where you can enter a number, click a button, and it will multiply the number by two and display the result. However, right now, the code opens ...

Ways to calculate the memory utilization of a JavaScript object

Suppose I want to compare the efficiency of storing bits of a static canvas/image with Alpha more or less than 0.5 using an "array of array of number" versus an "array of string," which would be better in terms of memory usage and speed? var c = $('m ...

What is the best way to close all modal dialogs in AngularJS?

Back in the day, I utilized the following link for the old version of angular bootstrap: https://angular-ui.github.io/bootstrap/#/modal var myApp = angular.module('app', []).run(function($rootScope, $modalStack) { $modalStack. dismissAll( ...

The .AppendChild() method does not appear to be working as expected following the completion of

Encountering a peculiar problem here. The scripts run smoothly, but the content doesn't display on screen until I "inspect element" and then close the inspector window or zoom in/out. It's not an issue with the "display" CSS property because even ...

Capturing and saving location data without internet connection, and then displaying markers once connectivity is restored

I am currently developing a web application that will monitor the user's location. I want to ensure its reliability, so even if the user loses internet connection, the application will continue tracking their location (since GPS does not rely on inter ...

Vue.js encountered an error while trying to load the component: either the template or render function is not

Currently I am delving into the realm of Vue.js paired with Laravel by following this series, where the narrator seems to breeze through without encountering any errors. Unfortunately, when I attempted to change the route, a pesky error made an appearance. ...

I encountered difficulty accessing a different domain from the node server

I am currently in the process of integrating the PayUmoney payment gateway into my MEAN stack application. I have successfully retrieved all mandatory fields from the Angular controller to Node and even generated the Hash key. However, when attempting to r ...

Adding multiple clones of Node to an array of objects using a POST request

I am working with a mongodb model that has the following structure: ingredients: [ quantity: Number, measurement: String, name: String ] Currently, these ingredients are being inputted through a single form where users can add new ingredients by cl ...

Can we verify if this API response is accurate?

I am currently delving into the world of API's and developing a basic response for users when they hit an endpoint on my express app. One question that has been lingering in my mind is what constitutes a proper API response – must it always be an o ...