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

Exploring Vue with Typescript - leveraging components without explicit definitions

Has anyone successfully used vue-instant component as a child component before? I'm having trouble adding components without definition. Could it be related to webpack config ignoring node_modules due to lack of type declaration? Here's the code ...

The property is not found in the '{}' type but is necessary in the type... Typescript connect strategy

Hello, I am currently trying to establish a connection pattern for React with TypeScript. I have a reducer set up as follows: type State = { version: number, a?: string } interface ActionC { type: string payload?: number } type IAction = Action ...

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...

Making an Http Get request in Angular 2 by passing a JSON object

How can I make an HTTP GET request and send a JSON object along with it? Here is the JSON object: {{firstname:"Peter", lastname:"Test"} I want to pass this object in the HTTP request to receive a list of matched persons. Is this possible? The example o ...

Activate the field once the input for the other field is completed

I have a form where the last name field is initially disabled. How can I make it so that the last name field becomes enabled only when the first name is inputted? <form> <label for="fname">First name:</label><br> ...

Navigation arrows for sliding`

Is there a way to add custom right/left arrows to the Ionic slider component? Demo: Check it out on Stackblitz Note: Make sure to refer to the home.html page for more details. .html <ion-slides [pager]="true" [slidesPerView]="2"> <ion ...

Creating an Http interceptor in Ionic 3 and Angular 4 to display a loading indicator for every API request

One of my current challenges involves creating a custom HTTP interceptor to manage loading and other additional functions efficiently. Manually handling loading for each request has led to a considerable increase in code. The issue at hand: The loader is ...

What sets Import apart from require in TypeScript?

I've been grappling with the nuances between import and require when it comes to using classes/modules from other files. The confusion arises when I try to use require('./config.json') and it works, but import config from './config.json ...

Firebase Integrations: How to Handle Errors in External API Calls within Firebase Functions

My current challenge involves retrieving data from an external API using Firebase functions and displaying it in an Angular application hosted on Firebase. Billing is enabled for the project. The API call works fine on localhost, but fails to fetch data wh ...

Angular: how to manually trigger change detection without using Angular's dependency injection system

Is there a way to globally initiate angular change detection without having to inject something like ApplicationRef? I am looking to utilize the functionality as a standard JavaScript function rather than a service method, in order to avoid the need for ...

Having trouble with obtaining precise mouseup and mousedown coordinates

Currently, I am working with react and typescript for my project. I have implemented a canvas element where I am attempting to draw a rectangle based on mouseup and mousedown events. However, the issue I am facing is that the rectangles are being drawn in ...

Ensure the validity of Google Identity CredentialResponse JWT with Node.js

I am in the process of integrating Google Sign-In on one of my websites using the callback method. So far, everything seems to be working well; when a user clicks a button, a network request is made, and a JWT is received. Now, I would like to verify and ...

Guide on accessing device details with Angular2 and Typescript

I'm working on populating a table with details using TypeScript, but I need some assistance. 1. Device Name 2. Device OS 3. Location 4. Browser 5. IsActive I'm looking for a solution to populate these fields from TypeScript. Can anyone lend me ...

Having difficulty connecting to the router within a container component for Angular2 routing

Presently, my code snippet looks like this: import { Router } from 'angular2/router'; @Component({...}) export class Index { constructor(public router: Router) { this.router.subscribe({...}); } } Although there are additional function ...

Troubleshooting issues with setting errors on a FormGroup instance in Angular Reactive Forms are proving to be more challenging

Currently I am working with Angular 4.4.3 reactive forms to create custom validation for a group of controls within a form. As per the documentation on AbstractControl.setErrors, this method updates the errors property of the AbstractControl that it's ...

Next.js routing can sometimes be unpredictable, especially when navigating from a nested route

I recently set up a directory named dashboard within the pages folder, and it contains the following files: index.tsx customers.tsx invoice.tsx items.tsx When a user navigates to http://localhost:3000/dashboard, the index.tsx page is displayed. However, ...

Utilizing ASP.NET Core MVC in conjunction with Angular and Identity Server 4 for seamless integration with web API connections

Posting here after receiving a response from this post -------------------------------------- In the midst of developing an application with an MVC core app that loads an angular application. The angular app will connect to a Web API for CRUD operations. ...

Learn how to implement autofocus for an ng-select element within a bootstrap modal

When working with ng-select inside a modal, I am facing an issue with setting autofocus. While I am able to add focus for the input field within the modal, the same approach doesn't work for ng-select. Can anyone provide guidance on how to set focus f ...

Facing challenges with parsing JSON files in an Angular 2+ application

Utilizing the Angular CLI, I have configured this project with the standard folder layout. My goal is to practice reading a JSON file from src/app/assets/items.json and then using it to display these items in the HTML. items.json: { "results": [ ...

Error in Reactive Form: Null Property Reading Issue

Issue: Encountered a Cannot read property errors of null error in the form group. I have implemented a reactive form with validation, but I keep running into this specific error. Here is the complete form control setup: <div class="container mt- ...