What could be the possible reason for the token having a null value during login authentication in

As a beginner to Angular, I am facing an issue with my JWT login page implementation. Despite printing the token in the console and confirming its existence as a string, I am receiving a null (or undefined) value. This is the code snippet from my UserService.ts:

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { serializeNodes } from '@angular/compiler/src/i18n/digest';
import { tap } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class UserService {

  baseurl = "http://127.0.0.1:8000";
  httpHeaders = new HttpHeaders({'Content-Type':'application/json'});
  constructor(private http: HttpClient) { }

  login(username, password): Observable<any>{
    return this.http.post<{token:  string}>(this.baseurl + '/api/v1/rest-auth/login/', {username, password}).pipe(
      tap(
        res => {
          localStorage.setItem('token', JSON.stringify(res.token));
      }))
  }
  
  // Other methods of UserService follow...

Concerns were raised regarding the getToken function within UserService where the error encountered was SyntaxError due to an unexpected token. The relevant code snippets are shown below:

// Code snippet from UserService.ts

getToken(){
  return localStorage.getItem('token');
}

The next segment of code is related to JwtService.ts:

import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { UserService } from './user.service';

@Injectable({
  providedIn: 'root'
})
export class JwtService implements HttpInterceptor{

  constructor(private injector: Injector) { }

  intercept(req, next){
    let serv = this.injector.get(UserService)
    let tokenizedReq = req.clone({
      setHeaders: {
        Authorization: `Bearer ${serv.getToken()}` 
      }
    })
    return next.handle(tokenizedReq)
  }
}

Login.component.ts contains the logic for handling user login and token retrieval:

// Code snippet from Login.component.ts

login(){
  this.api.login(this.username, this.password).subscribe(
    response => {
      this.token = response;
      console.log(response);
      alert(response)
      this.router.navigate(['/student'])
      console.log(this.api.loggedIn)
    },
    error =>{
      console.log("An error occurred");
      console.log(error)
    }
  );
}

The final piece of the puzzle lies within app.modules.ts:

// Code snippet from app.modules.ts

// Necessary imports and declarations 

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    NavigationComponent,
    LoginComponent,
    StudentComponent,
    DeanComponent,
    AdminComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtService,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

In conclusion, despite efforts to troubleshoot the issues, such as using JSON.parse method in getToken, the problem persists with the 'object Object' result upon executing alert in login.component.ts.

Answer №1

Issue Resolved. The error was found in the login function within the UserService module. The line of code needing correction should be as follows:

localStorage.setItem('token', res.key);

I have decided to keep this information here for future reference, in case someone encounters a similar issue.

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

The Angular dependency provider is failing to supply the requested alternative class

I am currently in the process of writing unit tests for the doc-manager.component component. This particular component relies on the DocService, but I want to swap it with instances of MockedDocService within my tests. By leveraging alternative class prov ...

Make sure that every component in create-react-app includes an import for react so that it can be properly

Currently, I am working on a TypeScript project based on create-react-app which serves as the foundation for a React component that I plan to release as a standalone package. However, when using this package externally, I need to ensure that import React ...

Error: JSON parsing error - Unexpected token at the start of the JSON data when using JSON.parse() function

Backend code router.route('http://localhost:5007/api/media') .post(mediaCtrl.saveMedia) async saveMedia(req, res) { let file = req.files.file let ext = req.body.extension let path = req.body.path if(_.isNull(file) || _.isEmp ...

Exploring the world of unit testing in aws-cdk using TypeScript

Being a newcomer to aws-cdk, I have recently put together a stack consisting of a kinesis firehose, elastic search, lambda, S3 bucket, and various roles as needed. Now, my next step is to test my code locally. While I found some sample codes, they did not ...

Issue: Unable to find 'rxjs/add/operator/map'

In the app.module.ts file, I have attempted to import the map in various projects and it worked smoothly. However, in this particular project, it seems to be causing some issues. import { BrowserModule } from '@angular/platform-browser'; ...

There are no route parameters defined

Within my user template file, I have a tab control implemented as shown below: <nav md-tab-nav-bar> <a class="tab-label" md-tab-link [routerLink]="'following'" routerLinkActive #following="routerLinkActive" [acti ...

When the data is not initialized within the ngOnInit() function, the p-dataTable does not bind properly

In the process of building a form, there is a specific dialog available for users to input data. The dialog functions within a larger form structure. Once the user finishes entering their data in the dialog and clicks on the SAVE button, the entered inform ...

The creation of fsm.WriteStream is invalid as it is not a recognized constructor

Can you help me with this issue? I am attempting to install @ng-idle/keepalive using the command npm install --save @ng-idle/core, but I encountered the following error: npm ERR! fsm.WriteStream is not a constructor npm ERR! Log files were not written due ...

What is the best way to retrieve the name of a static method within a class?

In my code, I am logging multiple messages in a static method and I want to use the method name as context. However, I do not want to create a separate variable called `context` and assign the function/method name to it. I would like to be able to access ...

Destructuring an array of strings for use as parameters

Hey guys, I'm working with an array of keys here Example 1: let keyArray = ['x', 'y', 'z'] I'm trying to find a way to use these keys as parameters without repeating them multiple times. Do you have any suggestions ...

Subscribing to Observables in Angular Services: How Using them with ngOnChanges Can Trigger Excessive Callbacks

Consider the following scenario (simplified): Main Component List Component List Service Here is how they are connected: Main Component <my-list [month]="month"></my-list> List Component HTML <li *ngFor="let item in list | async>&l ...

Attempting to leverage the combination of mocha, ES6 modules, and ts-node while utilizing the --experimental-loader option

I've been attempting to make the ts-node option --experimental-loader function alongside mocha, but so far I haven't had any success. Before I started compiling ES6 modules, running mocha tests was as simple as: "test": "nyc --reporter=html mocha ...

Exploring the world of Angular, .NET Core, and managing server

Is it still common practice to utilize server sessions for storing information? I have a website built in Angular with a C# backend, and currently, whenever the frontend requires data, it fetches it from the backend via its API. This results in the backend ...

Mastering the Art of Sharing PrimgNg Selected Checkboxes with Child Component Dropdown

I am developing a simple application using PrimeNg. In order to pass information from the selected items of a Multi-Select component in the parent element (<p-multiSelect/>) to a Dropdown component in the child element (<p-dropdown/>), I have i ...

Displaying errors from an API using Angular Material mat-error

I am currently working on a form that includes an email field. Upon saving the form, the onRegisterFormSubmit function is called. Within this function, I handle errors returned by the API - specifically setting errors in the email form control and retrie ...

Modifying tooltip format in React ApexChart from dots to commas

I am in the process of creating an app targeted towards German users, who traditionally use commas (20,00) instead of dots (20.00) for numbers. I am using react-apexcharts and struggling to figure out how to replace the dots with commas in both my chart an ...

The issue with Angular Material Dialog hiding certain elements

In my Node.js Angular project, I am trying to implement a confirm dialog which should be a simple task. Utilizing Material styling to speed up development process. However, upon running the project, the opened dialog appears to be empty: The structure of ...

The property 'x' cannot be found on the data type 'true | Point'

I am dealing with a variable named ctx which can be either of type boolean or Point. Here is how Point is defined: type Point = { x: number y: number } In my React component, I have the following setup: const App = () => { const [ctx, toggleC ...

Error message encountered during angular project build using ng build: angular.json file missing

I had successfully created a project on my laptop a month ago and didn't encounter any errors. However, when I cloned the repository to a new computer today, I encountered some issues. After running 'npm i' to install packages, I attempted t ...

How can I adjust the timeout or enhance my code for Excel Online's ExcelScript error regarding the Range getColumn function timing out?

I am struggling with a code that is supposed to scan through the "hello" sheet and remove any columns where the top cell contains the letter B: function main(workbook: ExcelScript.Workbook) { let ws = workbook.getWorksheet("hello"); let usedrange = ws ...