Angular - Error: Object returned from response does not match the expected type of 'request?: HttpRequest<any>'

While working on implementing an AuthGuard in Angular, I encountered the following Error:

Type 'typeof AuthServiceService' is not assignable to type '(request?: HttpRequest) => string | Promise'. Type 'typeof AuthServiceService' provides no match for the signature '(request?: HttpRequest): string

This snippet shows my auth-service.service.ts file:

@Injectable({
  providedIn: 'root'
})
export class AuthServiceService {

  constructor(
    private http:HttpClient,
    public jwtHelper: JwtHelperService) { }
  
  login(data):Observable<any>{
    return this.http.post(baseUrl + 'ApplicationUser/login' ,data)

  }

  handleError(error: HttpErrorResponse) {
    return throwError(error);
  }

  public isAuthenticated(): boolean {
    const token = localStorage.getItem('token');
    return !this.jwtHelper.isTokenExpired(token);
  }

}

And here is my AuthGuard Service implementation:

import { AuthServiceService } from 'src/services/auth/auth/auth-service.service';
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {

  constructor(public auth: AuthServiceService, public router: Router) { }
  
  canActivate(): boolean {
    if (!this.auth.isAuthenticated()) {
      this.router.navigate(['']);
      return false;
    }
    return true;
  }
}

The error arises on the line defining tokenGetter in JWT_Module_Options:

const JWT_Module_Options: JwtModuleOptions = {
  config: {
    tokenGetter: AuthServiceService
  }
};

I'm seeking assistance in understanding what the response from AuthService should entail. Any guidance would be greatly appreciated.

Answer №1

After conducting some research, I was able to discover the solution. The tokenGetter Option requires a string containing my token - so I retrieved the token from local storage as shown below:

const JWT_Module_Options: JwtModuleOptions = {
  config: {
    tokenGetter: () => {
      return localStorage.getItem('token')
    }
  }
};

Now my AuthGuard is functioning correctly :) I appreciate all the assistance! :)

Answer №2

It appears that your code is mostly correct, however there is an issue with initializing a method inside the constructor.

 constructor(private http:HttpClient,
    public jwtHelper: JwtHelperService) { }
  login(data):Observable<any>{
    return this.http.post(baseUrl + 'ApplicationUser/login' ,data)

  }

To fix this, make the following changes:

  constructor(private http:HttpClient, public jwtHelper: JwtHelperService) { }
    
  login(data): Observable<any> {
      return this.http.post(baseUrl + 'ApplicationUser/login' ,data)
  }

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

Every day, I challenge myself to build my skills in react by completing various tasks. Currently, I am facing a particular task that has me stumped. Is there anyone out there who could offer

Objective:- Input: Ask user to enter a number On change: Calculate the square of the number entered by the user Display each calculation as a list in the Document Object Model (DOM) in real-time If Backspace is pressed: Delete the last calculated resul ...

Using TypeScript's reference function within an HTML document

It feels like ages since my early days of web development. Back when I first started coding, we would reference a script using a <script> tag: <html> <head> <script src="lealet.js"></script> <!-- I know the path isn´t c ...

Angular 6 form template issue: 'No directive found with "exportAs" attribute set to "ngForm"'

I recently downloaded a free skin for Angular 6 + Bootstrap 4 from here. However, I keep encountering the following error message: "There is no directive with 'exportAs' set to 'ngForm'." In my app.module.ts file: import {CommonModule ...

Typescript - any of the types imported from a module

Currently, my code looks like this: import * as Types from '../schema/types'; and I'm looking to achieve something along the lines of: let a: Types; This would signify that a should be one of the various types exported from the file types. ...

Error thrown by FAIconLibrary addIcon method has commenced

I recently created an FAIcon Module and utilized the FaiconLibrary.addIcons() method to incorporate a few icons. Everything was functioning smoothly until I updated my project by running npm install, after which I started encountering the following error. ...

Creating a Union Type from a JavaScript Map in Typescript

I am struggling to create a union type based on the keys of a Map. Below is a simple example illustrating what I am attempting to achieve: const myMap = new Map ([ ['one', <IconOne/>], ['two', <IconTwo/>], ['three ...

"Enhance your slider experience with React Alice Carousel: place dot controls directly over images for

I am currently working with react-alice-carousel and I'm looking to adjust the placement of the dot controllers on the slider. Instead of their current position, which you can see in this image (https://i.sstatic.net/mi6eD.png), I want them to be loca ...

Setting a default value for NULL property in TypeScript

Trying to establish a default value for all NULL objects has been quite the challenge. The current code looks like this: private setDisplayAmount(summaries: summary[]): void { summaries.map(t => { // performing some operations, and then... ...

Adding a timestamp or hash as a request parameter for css or js files in the NextJS 12 build file can be accomplished by simply including "?ts=[timestamp]" in the file

It is important for me to be able to generate the following JavaScript and CSS file names with timestamps after building a NextJs application: ./path/file.js?ts=[timestamp] ./path/file.css?ts=[timestamp] ...

Implementing conditional where clauses in Firestore queries with dynamic parameters

Consider this scenario: I have a dynamic filter list for my product list, and I want to send an HTTPS request to a cloud function based on the selected filters. However, when trying to set multiple conditional where clauses from that request... The multip ...

Managing the ERR_NAME_NOT_RESOLVED issue

Currently, I am facing a task related to the health check endpoint where I need to receive a response from the backend or encounter a net::ERR_NAME_NOT_RESOLVED error if we are outside of a specific network. When attempting to send a request to my endpoin ...

Access the file in response to the angular2 message

Forgive my ignorance, but I'm curious to know how to effectively prompt the user to download a file sent by the backend through the response. Can anyone shed some light on this? ...

Announce enhancements to a Typescript library

Utilizing Sequency's extendSequence() feature to enhance all Sequence instances with a custom method: import Sequence, { extendSequence, isSequence } from 'sequency' import equal from '@wry/equality' class SequencyExtensions { e ...

Can Typescript automatically determine the return type based on the function argument value?

How can Typescript be utilized to deduce the return type from the valueType parameter instead of using overloads? type ValueType = 'integer' | 'string' | 'number' | 'date' | 'dateTime' | 'boolean&apos ...

Performing unit testing on a Vue component that relies on external dependencies

Currently, I am in the process of testing my SiWizard component, which relies on external dependencies from the syncfusion library. The component imports various modules from this library. SiWizard.vue Imports import SiFooter from "@/components/subCompon ...

Arranging the output of a Typescript project

I'm currently advocating for Typescript to be implemented in our web application. Can anyone provide insight on the best method for structuring Javascript output files? Should they be excluded from source control? And when it comes to testing, is it p ...

Using Generic Types in TypeScript for Conditional Logic

To better illustrate my goal, I will use code: Let's start with two classes: Shoe and Dress class Shoe { constructor(public size: number){} } class Dress { constructor(public style: string){} } I need a generic box that can hold either a ...

Incorporating an additional ion-item alongside the existing one instead of substituting it

I am retrieving a list of questions from an API with pagination. I have a button that triggers a function to load the next page of questions. Instead of replacing the previous page, I want to append the new questions below the existing ones. Here is my cur ...

The TypeScript error TS7006 is indicating that the parameter '_' is assumed to have an undefined type

In my Angular application, I have a class that implements ControlValueAccessor from the '@angular/forms' library: export abstract class CustomControl implements ControlValueAccessor { private _value: any = ''; private onChange ...

The validation for the prop 'setLoading' is not defined

Currently, I am utilizing React version 17.0.2 along with Typescript for my project. My aim is to transfer the setLoading function from the parent component (App) to the child component (About) so that the loading state within App can be altered from About ...