How to Utilize a Service in an Angular 2+ Module Declaration Using an Exported Function

Here is my module declaration with a service:

import { ConnectionService } from './services/connection.service';
import { NgModule } from '@angular/core';
import { Http, RequestOptions } from '@angular/http';
import { AuthHttp, AuthConfig } from 'angular2-jwt';

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
    tokenName: 'token',
    tokenGetter: (() => sessionStorage.getItem('token'))
  }), http, options);
}

@NgModule({
  providers: [
    {
      provide: AuthHttp,
      useFactory: authHttpServiceFactory,
      deps: [Http, RequestOptions]
    }
  ],
})

export class AuthModule { }

The service looks like this:

import { Injectable } from '@angular/core';

@Injectable()
export class ConnectionService {
    id;

    getToken() {
        return JSON.parse(sessionStorage.getItem('token'))[this.id];
    }
}

I am trying to utilize the "getToken" method from the service in the "tokenGetter" of the module's exported function, but I am struggling to get it to work. I have searched on Google for a solution without success so far.

Answer №1

Hello, would you kindly attempt it in this manner?

Creating an authentication HTTP service factory:

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
       tokenName: 'token',
       tokenGetter: (() => new ConnectionService().getToken())
       }), http, options);
 }

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

Using Node module in TypeScript/SystemJS

Attempting to utilize the React Blueprint library, I proceeded by executing a npm install and then attempted to import it as follows: import { Spinner } from "@blueprintjs/core" This resulted in an error message stating system.src.js:1051 GET http://loca ...

Is it necessary to have a Test Adapter in VSTS in order to include a code coverage report?

Currently, I am producing code coverage using Karma-coverage and hosting my output coverage folder on an http-server for local viewing. My question is: How can I display this report on the VSTS code coverage tab? Do I need to re-format my coverage result ...

Tips for converting a callback's return value into a string

I'm working with a TypeScript code that involves an array called data. This array is structured like [ {employee:"Jason",employeeRole:"teacher",id:10,gender:"male"}, {employee:"Mark",employeeRole:"student",id:10,gender:"male"}, ... ]. My task is t ...

Swapping elements in an *ngFor loop using Angular/Ionic

In my quest to create a dynamic list of items using the Angular directive *ngFor, I have come up with the following structure: Text - Image Image-Text Text - Image Image-Text https://i.sstatic.net/QgLdr.png <ion-grid> <ion-row *ngFo ...

There is no 'next' property available

export function handleFiles(){ let files = retrieveFiles(); files.next(); } export function* retrieveFiles(){ for(var i=0;i<10;i++){ yield i; } } while experimenting with generators in T ...

How to add a custom width to a p-column in PrimeNG within an Angular HTML template

I am trying to assign unique widths to each column in my columns using [style] based on the example given. I attempted to use [style]="{'width.px':'column.length + 10'}", but unfortunately, 'column.length' isn't functioni ...

What steps should I take to resolve the issue where the type 'Action' does not have a property named 'map'?

Within my ionic3/angularfire2 project, I am encountering an issue with connecting to a Firestore DB and retrieving a snapshot observable of a document. After conducting research online, I have noticed that others have used similar syntax successfully, but ...

The Angular 2 dropdown menu isn't populating because of the sluggish http response

I encountered an issue while trying to populate a dropdown list with data from an HTTP response using an Angular2 service. Below is the method in my service: categories: any; getCategories() { let subscription = this.httpclient .get ...

Angular 5/6: Issue detected - mat-form-field must have a MatFormFieldControl inside

I'm experiencing an issue while trying to open an OpenDialog window from a table list. The error message I encountered is as follows: ERROR Error: mat-form-field must contain a MatFormFieldControl. Below is the HTML code for the openDialog: <h2 m ...

How to Deactivate a Submit Button in Angular 2+ Template-Driven-Form Using a Child Component

When working with template-driven forms in Angular 2+, I encountered a challenge. I wanted to utilize child components within a form to facilitate unit testing of form elements. My goal was to disable the submit button using template reference variables, s ...

Using TypeScript with React and Material-UI: Issue with undefined theme in createStyles()

Currently, I am delving into React with TypeScript and utilizing the Material UI framework for the frontend. In my quest to activate media queries, an error has crossed my path: Uncaught TypeError: Cannot read property 'up' of undefined ...

Error: Attempting to access the 'user' property of a null value

I need help passing a unit test for my isAdmin() function. The function is supposed to return a role, but I keep getting an error that says 'user' cannot be read. I think the issue lies in how I am handling the user information provided by curren ...

Steps for downloading a file in Angular when the file is received as application/octet-stream

I am in the process of developing a website where I need to retrieve a file in CSV format using a REST API. However, when trying to access the API, I encounter an error, possibly due to the file being converted to JSON. How can I fetch and manage the file ...

TestCafe Environment Variables are not properly defined and displaying as undefined

Exploring TestCafe and diving into the world of automated testing. Trying to master the tools with guidance from Successfully executing code on my Windows setup! fixture`Getting Started`.page`http://devexpress.github.io/testcafe/example`; test("My ...

Let's define JSON data using Record<> and verify the presence of a specific key

When my backend sends a JSON object with id strings mapping to data, I make use of the Typescript type Record. Since some ids may not exist, I define it as: let data: Record<string, number | undefined> = { 'asdf': 1 }; To process this ...

Conceal an HTML element by utilizing *ngIf in Angular after a user clicks away from the designated area

Is there a way to implement an eventlistener on a <div> or another element, in order to hide a displayed item controlled by an *ngIf in Angular, when the user clicks away from that element? Context: I have a customized CSS dropdown that appears usin ...

"Upon submitting a form in React JS, the components will automatically trigger a

Within my application, there is a Mobx storage in conjunction with a modal window component. The form within the modal window allows me to collect all the properties and push them into an array named 'cart' within the storage as an object. Take a ...

Using TypeScript to test a Vue3 component that includes a slot with Cypress

I'm currently facing challenges setting up a new project. The technologies I am using include Vue3, TypeScript, and Cypress. It seems like the problem lies within the TypeScript configuration. Below is a Minimal Working Example (MWE) of my setup. Any ...

Encountering a Module Federation integration error while setting up Next.js 14 with App Directory: NextFederationPlugin

Currently, I am in the process of developing a micro-frontend application using Next.js 14.2.5 in combination with Module Federation. To initiate this project, I utilized the following commands to create two separate applications: npx create-next-app mf-ho ...

Guide to integrating a fruit product checklist within a React application

Seeking assistance in incorporating a checklist into my react application, to only be visible after a specific button is clicked. Upon reviewing productFruit's documentation, it appears that I need to utilize the following code snippet: useEffect(() ...