In order to access the localStorage from a different component, a page refresh is required as it is

UPDATE: Just to clarify, this question is NOT duplicate of how to retrieve the value from localstorage. My scenario is unique and the issue lies with Angular itself rather than localStorage.

I am currently developing an Angular7 application.

In one of my components, I set a token in localStorage using:

window.localStorage.setItem("oauth_token", oauth_token)
and then navigate to the home page: this.router.navigate(['/'])

However, when trying to access this token from the root component using

window.localStorage.getItem("oauth_token")
, the value returned is null unless I manually refresh the page.

Oddly enough, when checking the Chrome dev tools, the token is present in the local storage. So why does it require a page refresh? What steps can I take to resolve this issue?

Answer №1

The issue is not directly related to local storage. In order to access local storage or reflect any changes in the data, your root component needs a trigger or refresh.

When you navigate back to the home page, only the code within the home page component gets executed, not the parent or root component.

To address this, you should declare a variable in a service file. Whenever the local storage is updated, make sure to update the value of this variable in the service file. This variable can then be accessed in your root component. This way, any change in the service variable will trigger an update in the local storage. Here's a sample code: https://github.com/resistcheat/angular-variable-as-observable

Create a new Service File:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CommonService {
  data: any;
  private items: BehaviorSubject<any> = new BehaviorSubject<any>(this.data);
  items$: Observable<any> = this.items.asObservable();
  constructor(private http: HttpClient) { }
  setLocalStorageData() {// Call this function to set localstorage
    localStorage.setItem("oauth_token", oauth_token)
    this.data = oauth_token;
  }
}

//A trigger will fire when this.data changes. Add the following code to your root Component:

constructor(private commonService: CommonService) { }
items: any;
subscription: Subscription; //import { Subscription } from 'rxjs';

ngOnInit() {
  this.subscription = this.commonService.items$.subscribe(items =>  {
    this.items = JSON.stringify(items));
    console.log(localStorage.getItem("oauth_token"));
  }
}

ngOnDestroy() {
  this.subscription && this.subscription.unsubscribe();
}

Answer №2

Attempt to execute the code without using the window object:

localStorage.getItem("oauth_token")...

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

TypeError: "Table" has not been declared

This is my first experience with the script editor. I have been given the task of creating a pivot table for Google Sheets using a script. // This script creates a pivot table in Google Sheets function createPivotTable() { var ss = SpreadsheetApp.getAc ...

The anchor link is not aligning properly due to the fluctuating page width

Seeking help to resolve an issue I'm facing. Maybe someone out there has a solution? The layout consists of a content area on the left (default width=70%) and a menu area on the right (default width=30%). When scrolling down, the content area expand ...

Using jQuery to dynamically swap out <tr> tags and all the elements inside of them

In order to enhance user experience, I am looking to automatically fill in certain form elements within a table when a link is clicked. The intention is for the fields to populate with predefined values and then convert into HTML paragraph elements, preven ...

The value stored within an object does not automatically refresh when using the useState hook

const increaseOffsetBy24 = () => { setHasMore(false); dispatch(contentList(paramsData)); setParamsData((prevState) => ({ ...prevState, offset: prevState.offset + 24, })); setHasMore(true); }; This function increment ...

Slim and Angular2 htaccess configuration

I am encountering an issue with my htaccess file and could use some assistance. My setup includes an Angular2 app (single page client side app, index.html) and a slim-v3 PHP REST API (index.php). The Angular2 app interacts with the REST API, and I would id ...

Conceal the ::before pseudo-element when the active item is hovered over

Here is the code snippet I am working with: <nav> <ul> <li><a href="javascript:void(0)" class="menuitem active">see all projects</a></li> <li><a href="javascript:void(0)" class="menuitem"> ...

What is the best way to include a new attribute in a TypeScript internal object?

I am trying to include a property declaration in the window.history object, but I received a TypeScript error message This is my code: const historyInstance = createHashHistory(); // npm hoistory module window.history.historyInstance = historyInstance; / ...

The success function of the Ajax request remains untouched by the response

My ajax call isn't triggering the success:function(resp){ ...} Despite receiving a response status of 200 and a non-null Json response. This is my ajax setup: $.ajax({ url: '/url/', type: 'GET', data: { pass_ ...

Bringing in an Angular2 project to the Phoenix framework

Currently juggling two interconnected projects - a Phoenix based website and API, along with an Angular2 application utilizing the API from Phoenix. My goal is now to integrate the Angular2 application into the Phoenix project, but I'm unsure of the b ...

Ways to bring in external javascript files in reactjs

I'm currently working on a form that requires the user to input their location. To achieve this, I have integrated the npm package react-geosuggest-plus. However, I want to avoid including <script src="https://maps.googleapis.com/maps/api/js?key=AI ...

When the class changes, V-for re-renders every component

Currently, I am in the process of changing classes for images based on their index using the moveIndex method and key events. While this works smoothly on computers, it seems to take significantly longer when implemented on TVs. The process runs smoothly w ...

React does not allow objects as children, but what if it's actually an array?

My function is encountering an error message that reads: "Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead." I am struggling to understand why this error is occurring. ...

Replace the function if it is specified in the object, otherwise use the default functionality

Having a calendar widget written in TypeScript, I am able to bind a listener to a separate function. However, I desire this separate function to have default functionality until someone overrides it in the config object passed to the constructor. Within th ...

Is the Typescript index signature limited to only working with the `any` type?

I recently made changes to my interface and class structure: export interface State { arr : any[]; } export const INITIAL_STATE: State = { arr: [] }; This updated code compiles without any issues. Now, I decided to modify the Interface to incl ...

Having trouble showing an image with jQuery after it has been uploaded

Currently, I have a URL that shows an image upon loading. However, I want to provide the option for users to replace this image using a form input. My goal is to display the uploaded image as soon as it's selected so users can evaluate it. I'm a ...

Unable to identify the pdf file using multer in node.js

const multer=require('multer'); var fileStorage = multer.diskStorage({ destination:(req,file,cb)=>{ if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype==='image/png') { ...

What is the process for configuring sendmail in a node.js environment?

After setting up Sendmail on my Nginx server and configuring SMTP for sending emails in my Node.js project, I still encountered issues with emails not being sent. I tried using Sendmail directly, but I'm unsure of how to properly configure it. Here i ...

Using Angular JS, apply multiple column filters within a table to refine the displayed data

I'm currently working on implementing a filter for multiple columns in a table that is being populated by the ng-repeat directive. <tr ng-repeat="descriptiveField in vm.descriptiveFieldList|filter:{name:vm.searchText}" ng-class-even="'even-bg ...

Descending through layers of a flattened array of objects

I've been diving into the world of array of objects and have successfully flattened them. Now I'm faced with the challenge of nesting them based on unique values at different levels. Currently, I'm using the reduce method to achieve this, bu ...

Dealing with Laravel and AJAX - Issue with Loading DIV

I find myself in a perplexing situation. Despite not encountering any errors in my apache logs or browser (chrome), I am faced with an issue that has left me baffled. On a specific page (localhost/admin/networks), I can click on an item from a database-ge ...