Storing Angular header values in local storage

saveStudentDetails(values) {
  const studentData = {};

  studentData['id'] =  values.id;
  studentData['password'] =  values.password;

  this.crudService.loginstudent(studentData).subscribe(result => {
    // Here should be the value of the header from backend to be stored in localstorage
    this.toastr.success('You are logged in', 'Success !', { positionClass: 'toast-bottom-right' });
    this.router.navigate(['/address']);
  },
    err => {
      console.log('status code ->' + err.status);
      this.toastr.error('Please try again', 'Error !', { positionClass: 'toast-bottom-right' });
 });

https://i.sstatic.net/9kxxI.png

I possess a JWT token that is placed in the Authorization header upon user login, and I am seeking a method to extract the token from the Authorization header and store it in local storage for usage across different routes. Any assistance on this matter would be greatly appreciated.

Answer №1

Check out the stackblitz link to see examples of what you are attempting to accomplish.

Make sure to include this line in your code:

localStorage.setItem('token',res.headers.get(TOKEN_NAME));

Furthermore, it seems that you are missing the Access-Control-Expose-Headers declaration, which specifies which headers can be exposed as part of the response by listing their names.

Answer №2

this.userService.authenticateUser(userData).subscribe(response => {
    localStorage.setItem('accessToken', response.headers.get('Token'));    
});

Answer №3

Storing the current URL in localStorage using the Javascript method 'setItem'.

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

Enhancing Angular version from 5.2.7 to 5.2.10

After creating an Angular project using an older CLI version, the default installation was Angular version 5.2.7. Now, I am looking to upgrade my application to the latest stable Angular build, which is 5.2.10. One of the main challenges I'm facing i ...

I am facing an issue with my ngx-translator in Ionic4 as it is unable to retrieve the current language

I am having an issue with the ngx-translator package where I am unable to set the default language in my application. Here is the code snippet from my app.module.ts: import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import ...

Angular Boilerplate is experiencing difficulties in properly reading ABP

Working on my boilerplate project, I am now diving into consuming backend services (using asp .net) in Angular through http requests. However, I encountered an issue when trying to implement the delete method in mycomponent.ts, as TypeScript was not recogn ...

What would be the optimal type for the second argument of the `simulate` method?

When using the simulate function, I am familiar with code like this: simulate("change", { target: { value: '7' } }); However, if my onChange function requires an object as a parameter, what should I pass in the second argument? interface myObj ...

How does one distinguish between the uses of "any" and "any[ ]"?

Exploring the Difference Between any and any[ ] An Illustrative Example (Functioning as Expected) variable1: any; variable2: any[]; this.variable1 = this.variable2; Another Example (Also Functioning as Intended) variable1: any; v ...

Unable to execute OAuth2 with Okta using angular-oauth2-oidc framework

Looking to create an authentication module for an Angular application using Okta as the identity provider and implementing the angular-oauth2-oidc flow. Following a guide here: . However, encountering errors when running the web app. How can I troubleshoot ...

`The validation in Angular 12 is successful, yet the mat-input remains invalid.`

Code snippet of Component- ngOnInit(): void { this.form = this.fb.group({ currentPassword: ['', [Validators.required], [this.matchCurrentPassword]], newPassword: ['', [Validators.required, Validators.minL ...

Developing the headers for a service using React.js

As someone new to ReactJs, I'm curious about the various methods we can use to include Headers in our service Url before making a call. While I'm familiar with how GET/POST Calls are made in angular Js after including headers, I'd like to l ...

Error Alert: Redundant Identifier in Angular 2 TypeScript Documents

After following the Angular2 TS Quickstart guide, I noticed duplicate files scattered across various folders in my project. For browser: typings/browser node_modules/angular2/typings/browser Regarding es6-shim: node_modules/angular2/typings/es6-shi ...

What is the process for eliminating the perplexing "default" attribute that has been inserted into JSON?

I recently came across the jsondata.json file: { "name": "John", "age": 30, "car": "ferrari" } Located in the same directory is a typescript file called main.ts where I simply output the json data using console.log import * as j from '. ...

Incorporate a JavaScript library into a personalized JavaScript file that is utilized within my Angular2 project

Integrating Machine Learning into my Angular2 project using the "synaptic.js" JavaScript library is my goal. After executing the command npm install synaptic --save I intend to execute a custom javascript file (myJsFile.js): function myFunction() { v ...

Never display mat-select panel when closed

In my current scenario, I am using the following template structure: <mat-select #select> <mat-option *ngFor="let option of optionsData"> {{ select.panelOpen ? option.viewValue : option.value }} </mat-option&g ...

Linking all styles with Angular 2

Is it possible to apply a style when the exact nature of that style is unknown? Consider a scenario where I have a model containing string variables defining styles, as shown below: myStyle1:string="margin-left:10px"; myStyle2:string="margin ...

Issue with generating source map files using Webpack 4 and ts-loader

What mistake am I making here? When I execute webpack -d --config webpack.config.js, the map file is not generated along with bundle files. Here is my webpack.config.js: const path = require('path'); module.exports = { mode: "development" ...

What is the best way to configure Jenkins to exclude or include specific component.spec.ts files from being executed during the build

Currently, I am facing an issue while attempting to include my spec.ts files in sonarqube for code coverage analysis. However, my Jenkins build is failing due to specific spec.ts files. Is there a way to exclude these particular spec.ts files and include ...

angular change digits to Persian script

I am trying to convert English numbers to Persian numbers in angular 4: persianNumbers = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"]; engli ...

What is the way to utilize kafkajs' testHelpers module in my test cases?

I need guidance on how to write unit and integration tests for the code in my Typescript project that utilizes the kafkajs NPM package. The kafkajs project recommends using the testHelpers module for testing, which is referenced in its own unit tests. Howe ...

Guide on integrating a dynamic element within another element in Angular

Imagine a scenario where we have the following html structure <div [innerHTML]="contentFromAPI | safeHTML"></div> The content retrieved from the api contains multiple HTML elements, resulting in a structure like this: <div> &l ...

Error in Typescript: Cannot assign type 'string[]' to type 'string'

I'm currently developing a project using Next.js with Typescript and .tsx files, and I'm utilizing Supabase as my database. While everything is functioning perfectly on localhost, I'm encountering an issue when trying to build the project o ...

Transform an Angular 4 application into a desktop application by utilizing Electron

After creating an application with Angular 4, I am looking to develop a desktop version. My research has pointed me towards using Electron as the best solution for this task. Can anyone provide guidance on how to convert my Angular 4 application into an El ...