Angular: Implement a method from a designated service as a useFactory provider within a module

One of the challenges I am facing in my Angular5 application is related to a module that I am using in the following way:

import *....
@NgModule({

  providers: [
    AuthentificationService,
    {
      provide: AuthHttp,
      useFactory: AuthentificationService.MYMETHOD,
      deps: [Http, RequestOptions, EnvVarsService, LocalStorageService, RouteNavigator, ReloadTokenEventService]
    }
  ]
})

export class AuthModule {
  constructor( ) {}

}

The issue lies in utilizing a custom method named MYMETHOD which is defined in my AuthentificationService

This is how my service looks like:

@Injectable()
export class AuthentificationService {

  constructor() {}

  public authHttpServiceFactory(http: Http, options: RequestOptions,
                                envVarsService: EnvVarsService,
                                localStorageService: LocalStorageService,
                                router: RouteNavigator,
                                reloadTokenEventService: ReloadTokenEventService) {

    return new AuthHttp(new AuthConfig({
      tokenName: 'X-Auth-Token',
      headerName: 'X-Auth-Token',
      noTokenScheme: true,
      noJwtError: true,
      tokenGetter: (() => this.getAccessToken(http, options, envVarsService, localStorageService, router, reloadTokenEventService)),
      globalHeaders: [{'Content-Type': 'application/json'}],
    }), http, options);
  }


  private getAccessToken(): Promise<string> {
         // SOME TREATMENT
    }
  }

}

However, it appears that I am unable to locate (AuthentificationService.MYMETHOD)

Any suggestions on how to tackle this?

Answer №1

Give this a shot, it should do the trick by utilizing an exported function and adding AuthentificationService to the deps array

export function customFactory(authService: AuthentificationService) {
     return () => authService.yourMethod();
}

providers: [
AuthentificationService,
{
  provide: AuthHttp,
  useFactory: customFactory,
  deps: [AuthentificationService, Http, RequestOptions, EnvVarsService, LocalStorageService, RouteNavigator, ReloadTokenEventService],
  multi: true
}
]

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

Adding a blank line in an Angular table using primeNG to display database information requires a specific method

In my Angular application, I am utilizing primeNG table to display data fetched from a database. The table comes with 'add' and 'delete' buttons for user interaction. To view the interface, click on this link: https://i.stack.imgur.com/ ...

Organizing routes in Express.js and AngularJS

Having trouble setting up an express + angular app. Successfully loaded the assets files into it. Upon examining my code for Express and the html file, it seems that Express is only returning the index.html file, causing all routes to return that file. ...

Typegoose and NestJS: The 'save' property is not found on this type

I recently started using typegoose and nestjs for my backend-server. In my pages.service.ts file, I already have a function called getPageById() to retrieve a single page by its ID. However, when trying to call this function from another function within th ...

Incorporate Monaco Editor into an AngularJS 1.X project

Due to the challenges presented in this particular issue, I am seeking an alternative JavaScript-based source code editor compatible with AngularJS 1.X. My current exploration has led me to consider utilizing Monaco Editor. While I have successfully execu ...

Node.js method convention - invoking self-defined functions

Consider a scenario where a Node module contains two functions, func1() and func2(). It is necessary for func1 to make a call to func2 during its execution. In order to test func2 independently, I have included both func1 and func2 in the exports by setti ...

Converting a string to a number, even if it contains non-numeric

Is there a built-in function that can directly convert a string containing non-numeric characters to a number in JavaScript, without the need for using str.substring() followed by parseInt()? For instance, how can I efficiently convert the string x1 to th ...

How can I create a full screen button in WebGL with HTML and JavaScript?

How can I create a WebGL full screen button using HTML and JavaScript? I've done multiple searches on this topic but couldn't find a suitable solution. However, I did manage to find a button that works for putting my page in full screen mode. &l ...

Creating a custom type in Typescript using a function for testing purposes

I have been exploring ways to limit my search capabilities to specific criteria. Let's say I have a model and some data like the following: interface UserModel { _id: string; username: string; party: UserPartyModel; } interface UserParty ...

Detecting Android devices

Issue: My website functions properly on desktop but has a problem with the carousel images skewing on iPhones. To address this, I created a separate CSS styling for iPhone devices and used a JavaScript function found online to detect iPhones and iPads. Un ...

What is the best way to pass multiple row values in a form field using AngularJS to a web API?

Is it possible to insert multiple row values in an AngularJS controller using a web api? <tr ng-repeat="rt in xxtt"> <td> <input type="text" class="form-control" ng-model="rt.name" required /> </td> <td> ...

Using Typescript to extract values from an array and apply them as filters on a Map

My code involves two maps: charamap and filterdata. The goal is to filter charamap so that it only displays data for items listed in filterdata. The expected result should be: [LOG]: ["Football":1, "Golf":0] However, the actual output is: [LOG]: ["Footba ...

Control the contents of the DOM using JavaScript in a single-page application

Is there a way to append a div element with p and h3 tags after the <product-list> component in Angular? When I try putting it inside window.onload(), it only works when the page is reloaded or refreshed. This approach doesn't work well in singl ...

Challenges Associated with Promises in JavaScript

I'm having trouble with the last line of code in my program and I need some help figuring out how to fix it. Specifically, I know that the second "then" statement needs to return resolve() but I'm not sure how to go about implementing this. Any t ...

Issue with exporting member in VS Code but not in console

I currently have a NestJS project (project A) with one module that utilizes the @nestjs/typeorm and typeorm packages. In my other NestJS project (project B), I plan to use this module. However, there is a potential issue. Project B contains entities that ...

Why is Vue JS throwing an error stating "undefined is not an object"?

After creating a Vue app on a single page .html file served by django, which consists of multiple components, I decided to transition this project into a full-fledged Vue.js project using the Vue CLI. Initially, I thought it would be a simple task to trans ...

Guide to eliminating hashtags from the URL within a Sencha web application

I'm currently developing a Sencha web application and I need to find a way to remove the "#" from the URL that appears after "index.html". Every time I navigate to a different screen, I notice that the URL looks like this: ...../index.html#Controller ...

Retrieve data stored in an array from the complete HTML document retrieved by an XMLHttpRequest

Here is a snippet of JavaScript code I am working with: var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.readyState === 4) { var response = req.responseText; console.log(response); } }; req.open('G ...

The modal window displays an error upon submission and prevents itself from closing

Below is the HTML code for a modal form: <form action="" class="cd-form" method="POST" id="signinform" onsubmit="return: false;"> <p class="fieldset" id="warningPanel"> <?php ShowAlertWarning(); ?> </p> <p ...

JavaScript code that moves to another div when a particular div option is clicked

Within my Asp.Net MVC project, I devised a user-friendly assistant to aid users. By formulating questions and their corresponding answers, selecting a question unveils the related answer. A problem arises when the question path becomes too lengthy, causin ...

What is the best way to define a signal within a class interface in Angular 17?

I’m working on setting up signals for my properties in class, which has been going smoothly so far. public varName = signal(''); However, I would also like to utilize the related interface. Unfortunately, I have not come across any documentati ...