What is preventing Angular from letting me pass a parameter to a function in a provider's useFactory method?

app.module.ts

   bootstrap: [AppComponent],
      declarations: [AppComponent],
      imports: [
        CoreModule,
        HelloFrameworkModule,
      ],
      providers: [{
        provide: Logger,
        useFactory: loggerProviderFunc(1),

      }]
    })

app.component.ts

@Component({
  selector: 'my-app',
  styleUrls: ['./app.component.scss'],
  templateUrl: './app.component.html',
})
export class AppComponent {
   constructor(private c:Logger){ 
   }
}

logger.ts

export class Logger {
  constructor(private msg: string) {
     console.log(this.msg);
  } 
}

Error:ERROR TypeError: factory is not a function at _callFactory

The value passed in the console is indeed '1', however, I encountered some errors immediately after. Interestingly, when I removed the parameter and simply used 'loggerProviderFunc', the errors disappeared from the console completely.

Answer №1

It is important to remember that the provideFactory: field in Angular requires a function, not the result of calling a function.

If you need to pass an argument, you can use an arrow expression like this:

bootstrap: [AppComponent],
  declarations: [AppComponent],
  imports: [
    CoreModule,
    HelloFrameworkModule,
  ],
  providers: [{
    provide: Logger,
    useFactory: () => loggerProviderFunc(1),
  }]
})

While I have not personally tested it, Angular may also allow invoking functions for useValue:. If this is possible, keep in mind that the function will only be called once, unlike a factory method which is invoked every time the resolver resolves something.

bootstrap: [AppComponent],
  declarations: [AppComponent],
  imports: [
    CoreModule,
    HelloFrameworkModule,
  ],
  providers: [{
    provide: Logger,
    useValue: loggerProviderFunc(1)
  }]
})

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

Continuously receiving the "Add to home screen" prompt despite already installing the PWA app

Is there a method to determine if the Progressive Web App has already been installed? It is possible to cancel the prompt event in the 'beforeinstallprompt' event. window.addEventListener('beforeinstallprompt', (event) => { // co ...

`Welcome to the World of AngularJS with IntelliJ IDEA`

Hey there! I'm currently diving into the world of Angular.js and IntelliJ IDEA, but seems like I've hit a roadblock. I'm attempting to create a basic "hello world" example from a book in the IDE, but it's just not cooperating. After dow ...

The sender parameter in runtime.onMessage does not include the tab information

I've implemented a browser action that triggers a message to be sent. chrome.browserAction.onClicked.addListener(function(tab) { var message = { 'message': 'overlay-intent' }; tab_message(tab.id, message); }); ...

PHP page Not Refreshing Properly Without Ajax

I am in need of assistance. Could someone please provide me with a code that has been thoroughly reviewed and tested for errors to address my issue? The program, 22.php, consists of a form. The desired functionality is for the user to enter information and ...

Angular - Customizing button bindings for various functions

As a newcomer to Angular and TypeScript, I am faced with the task of creating a customizable button that can display text, an icon, or both. For example: button-icon-text-component.html <button> TEST BUTTON </button> app.component.html & ...

Aggregate the values in an array and organize them into an object based on their frequency

I have an array of information structured like this: 0: { first: "sea", second: "deniz", languageId: "English-Turkish"} 1: { first: "play", second: "oynamak", languageId: "English-Turkish&qu ...

Adjusting the placement in Draw2D

I'm a newcomer to this library and I'm struggling to figure out how to properly size and position the canvas. If anyone could provide guidance on the best way to do this, I would greatly appreciate it. $(window).load(function () { // se ...

Leverage a single attribute from a Typescript interface within another interface

Let's imagine we have a TypeScript Interface like this export interface IMyObj { id: string; type: 'AA' | 'AZ' | 'XY'; ... } Now, I require another interface that includes the same type field export interfa ...

JavaScript 3D Arrays

Is there a way to create a 3D array similar to runes['red'][0]['test']? If so, how can I accomplish this? var runes = {} runes['red'] = [ 'test': ['loh'] ] runes['blue'] = {} runes[&apo ...

How can I extract a specific data value from a JSON file in Ionic 2?

Here is the JSON data: [ { "id": 1, "label": "saw", "total": "100" }, { "id": 2, "label": "saw1", "total": "300" }, { "id": 3, "label": "saw2", "total": "400" } ] Below is my Typescript code snippet: this. ...

Issues with image loading in Next JS and Cloudinary

I'm currently delving into the world of Next JS and attempting to convert my app into a static site. In doing so, I've opted to utilize Cloudinary for image processing; however, I'm encountering issues with the images not displaying. Next JS ...

script code to limit selection of dates within a predefined range

I'm seeking assistance to limit my customers from selecting a date beyond 10 days in advance. Although I previously had a code that functioned properly when there were more than 10 days left in the current month, it is now ineffective. This is becaus ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

Utilizing JQuery toggle feature to display extra content

Having some trouble with my JQuery toggle/collapse function. I added my own class "timelineEventWide" but it's not working as expected. As a JavaScript beginner, could someone please help me with the correct syntax? Thank you! e(".expandAll").toggle( ...

Unexpected response from http.request in NodeJS

When using the http.request module, I encountered a strange issue. My goal is to write a web crawler in NodeJS to fetch and parse data from this webpage. However, the response provided by http.request does not match the HTML rendered by Chrome. Below is ...

Using node.js version 10.0.0 to tinker with gulp

I was working on a node.js api project that functioned perfectly with node.js v8.1.4 & npm v5.0.3. However, upon transitioning to node.js v10.0.0 & npm v5.6.0, I encountered the following error: [email protected] ecosystem E:\opensource& ...

Ways to set a button as default clicked in an Array

I have a collection that stores languages and their boolean values. My goal is to automatically set buttons to be clicked (active) for each language with a true value in the collection. Whenever a different language is selected by clicking on its respect ...

What is the process for implementing angular-material's pre-defined theme variables in component styling?

I was trying to create a more dynamic background-color for my .active class within my mat-list-item Here is the HTML: <mat-list-item *ngFor="let page of pages" matRipple routerLinkActive="active" > < ...

How can I compare the current page URL with the navigation bar?

Looking to compare the URL of a current page to an element in the navigation bar using jQuery. Started by assigning the current URL to a variable: var currentPage = window.location.href; Then utilized an .each function to loop through each item in the n ...

Certain images are not being retrieved by Express on Linux, although they are functioning properly on Windows

When using a template to display HTML code, everything works smoothly on Windows. However, when transferring the code to a Linux machine, an issue arises - "Cannot GET /SmallVacImages/1.jpg". It seems that the index.html file can load images from the publi ...