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' });
 });

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

Troubleshooting data binding problems when using an Array of Objects in MatTableDataSource within Angular

I am encountering an issue when trying to bind an array of objects data to a MatTableDataSource; the table displays empty results. I suspect there is a minor problem with data binding in my code snippet below. endPointsDataSource; endPointsLength; endP ...

What is the most reliable way to create an array ensuring that all potential values come from a specific dictionary?

I am seeking a method to define the testArray so that only keys from the example dictionary can be inserted into the array. enum example { key1 = 'A', key2 = 2, key3 = '3', }; const testArray: ?? = [example.key1, example.ke ...

Unit tests in Angular failed due to unsuccessful HttpClient requests

My current challenge involves unit testing a service responsible for making HTTP calls. While I can successfully test requests returning a 200 status code, I am struggling to create tests for responses with other status codes. For instance, when the reque ...

What is the process of extracting multiple attributes from an object that has been selected by a user using mat-options (dropdown list) in Angular?

Summary: A dropdown list contains objects, unsure how to capture multiple attributes of selected object. Current Implementation: I have successfully created a dropdown list that displays the details of an object retrieved through an API call: <mat-f ...

@The value of @Input is consistently undefined

I'm using @Input to pass IDs into a child component, where they are used to filter the data set within that component. <div *ngIf="exerciseLength > 0"> <exercise [course]="Course" [filter-by-exercise-id]=""></exercise> </di ...

Encountered an error with create-react-app and MaterialUI: Invalid hook call issue

I am encountering an issue while trying to set up Create-react-app with Material UI. The error message I receive pertains to Hooks. Could there be something else that I am missing? This is the specific error message being displayed: Error: Invalid hook ...

Encountering an issue with setting up MikroORM with PostgreSQL due to a type

I'm currently working on setting up MikroORM with PostgreSQL, but I've encountered a strange error related to the type: Here is the code snippet: import { MikroORM, Options} from "@mikro-orm/core"; import { _prod_ } from "./consta ...

leveraging two connected hooks

I am facing a challenge where I need to utilize two hooks that are interdependent: useHook1() provides a list of ids, and useHook2(id) is called for each id to retrieve a corresponding name. Essentially, what I aim to achieve is: const [allData, setData] ...

Check out the selected values in Ionic 3

I am trying to retrieve all the checked values from a checkbox list in an Ionic3 app when clicked. Below is the code snippet: <ion-content padding> <ion-list> <ion-item *ngFor="let item of items; let i= index"> <ion-label>{{i ...

Narrowing Down State Types

I am working on a functional component in NextJS with props passed from SSR. The component has a state inside it structured like this: const MyComponent = ({err, n}: {err?: ErrorType, n?: N})=>{ const [x, setX] = useState(n || null) ... if(e ...

Mysterious attributes of angular 6's <table mat-table> tag

This particular question regarding the angular material table has not been duplicated in any other discussions. Other similar questions pertain to angular versions 2-5, not version 6 The issue I am encountering is as follows: Can't bind to 'dat ...

Tips for waiting for an observable loop

When using my application, the process involves uploading a series of images in order to retrieve the file IDs from the system. Once these IDs are obtained, the object can then be uploaded. async uploadFiles(token: string):Promise<number[]> { let ...

Issue with MIME handling while utilizing Vue-Router in combination with Express

Struggling to access a specific route in Express, I keep encountering an error in my browser. Additionally, when the Vue application is built, only the Home page and the 404 page seem to work properly, while the rest display a default empty HTML layout. F ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

Having trouble grasping the concept of Interfaces and dealing with FormGroup problems in Angular?

Apologies if my question is a duplicate, I have found several solutions for the same issue on Stack Overflow, but unfortunately, I struggle to understand them in technical terms. Problem 1 src/app/models/dataModel.ts:2:5 2 id: number; ~~ The exp ...

Decoding the logic behind the *ngIf directive

Context In my code template, I am iterating over data retrieved from an HTTP response. <div *ngFor="let method of paymentMethods"> Within this loop, I am displaying method?.payment_profile_id Now, I want to display one of two elements based on ...

Cricket score update features on the client side

Looking for assistance with client-side code development! I am currently working on an Android application using Ionic that involves live cricket scores. I have purchased a cricket API and understand how to connect to it using Node.js on the server side. ...

Why am I restricted to adjusting mat-elevation settings within the component's CSS exclusively?

In my Angular 8 project, I am utilizing Angular material to enhance the design of my material cards. To set up the shadow effect on these cards, I am using the elevation helper mixins provided in the documentation: https://material.angular.io/guide/elevati ...

Error thrown due to syntax issues in react.d.ts declaration file in TypeScript

Currently, I am attempting to integrate react with typescript in my project. However, typescript is generating syntax errors for the react.d.ts file sourced from Github: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/react The encountered ...

When using TypeScript's array intersection type, properties are not accessible when using methods like Array.forEach or Array.some. However, they can be accessed within a for loop

It was challenging to search for this problem because I may not have the correct technical terms, but I hope my example can help clarify it. Background: I am using query data selectors in react-query to preprocess query results and add some properties tha ...