Is it possible to inject services and pass parameters in the constructor in Angular and Typescript?

What options do I have if I want to modify the constructor for fooService in this service injection?

export class MyService {
    private fooService: IFooService;
    public static $inject  = [ "fooService" ];

    constructor(fooService: FooService) {
        this.fooService = fooService;
    }
}

Is it possible to pass a parameter to fooService when initializing it?

Answer №1

To perform calculations or set parameters during the run/config phase, utilizing a Provider is recommended.

class MyServiceProvider implements ng.IServiceProvider {
  private customParameter;

  public setCustomParameter(val) {
    this.customParameter = val;
  }

  public $get():Function {
    return () => {
      return new MyService(this.customParameter);
    };
  }
}

Incorporate the MyServiceProvider during the config phase and invoke the setCustomParameter function.

If you are aware of the parameter to be used, you can simply inject it using regular injection by defining an angular variable as follows:

angular.constant(CONSTANT_NAME, 'CONSTANT_VALUE');
export class fooService {
    public static $inject  = [ "CONSTANT_NAME" ];
    constructor(CONSTANT_NAME) {
    }
}

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

The Angular-Meteor package running on an Android device is encountering an error message stating "Unexpected token <"

Everything was running smoothly with my Angular-Meteor Cordova application until a minor change caused some trouble. Now, when I try to run meteor run android-device, the app attempts to start on the device but encounters issues loading the packages. Here& ...

Is it possible to implement dynamic routing in AngularJS using just one HTML page?

How can I dynamically display details of items from an array in Angular on the same page when clicked? Here is my code: <body ng-app="myApp" ng-controller="mobileController"> search:<p><input type="text" ng-model="test"></p> < ...

AngularJS: Injecting dependencies efficiently

Imagine a scenario where I have a service named httpservice, and there are multiple controllers and services (m and n being positive integers) in my application. In order to use this service across all components, the question arises: "Is there a way in an ...

What is the best way to integrate a page title with Angular?

Is there a recommended approach to dynamically loading the page title with Angular? I'm open to any suggestions or ideas you may have. Your input would be greatly appreciated. ...

Utilizing Redux with React class components: A comprehensive guide

I have been attempting to integrate Redux with React Class using TypeScript, following the guidelines provided in this tutorial. However, I am encountering numerous compilation errors and feeling overwhelmed as to where to begin troubleshooting. It is cl ...

Different Versions of Type in Typescript: Generic vs Non-Generic

Having a quick question here! How can I create two classes with generic type arguments in typescript? export class ServiceResponse { } export class ServiceResponse<T> extends ServiceResponse {} I encountered an issue where TypeScript flagged these ...

Using MUI ClickAwayListener to automatically close the modal upon clicking in React.Js

In order for the modal to work correctly, it should be visible when the 'More' button is clicked and should close when either the More button or any other part of the screen is clicked (excluding the modal itself). I've attempted different m ...

Create an array interface to begin

According to the information provided in the Handbook, it is possible to define a custom array interface with either string or number index: interface StringArray { [index: number]: string; } To demonstrate this concept, I created the following inter ...

Unique text: "Enhancing User Interaction: Using a custom directive to dynamically evaluate

Introduction: A simple demonstration of HTML structure: <td ng-repeat="col in cols"> <div ng-bind-html="col.safeHTML"></div> </td> JavaScript controller code snippet: $scope.cols = [ { field : 'logo&apos ...

Keeping certain pages hidden from specific users using Angular and PHP

I'm currently working on a website project that involves users creating profiles. The unique aspect of this site is that each profile will only be visible to users specifically selected by the creator, and not to everyone else. With the help of angul ...

Issue with saving objects using $cookies.putObject in Angular 1.4

Recently, I made the transition from angular version 1.2 to 1.3 and then to 1.4 which deprecated $cookieStore in favor of $cookies. Even after adding the line $cookies.putObject('user', user);, the data is not being saved to cookies (I confirmed ...

How long does AngularJS cache $http requests for?

Hey there! According to my understanding of the Angular documentation, this is how you can set the cache for an $http request: cache – {boolean|Cache} – If set to true, a default $http cache will be used for caching the GET request. Alternatively, ...

What sets apart ruby's HTTParty from angular's $http?

Using HTTParty to Post Request $http did not pass the http method properly. However, HTTParty functioned correctly and retrieved the desired results.</p> ...

Protractor encountered an issue when attempting to synchronize with the page, displaying the error: "angularJS testability and angular testability are both undefined."

Currently, I am in the process of developing end-to-end tests and I wanted to incorporate async and await functions into my code. Here is a snippet from the configuration file: exports.config = { framework: 'jasmine', seleniumAddress: & ...

What is the reason for requiring that the value type in a map must be uniform?

When using TypeScript, I expect the map type to be either a number or string, but unfortunately, an error is being reported. Click here for the Playground const map: Map<string, string | number> = new Map([ [ '1', &apo ...

The interconnected web of relationships between AngularJS components

Can the hierarchy of components in AngularJS be grasped and their relationships with each other understood? Are there any visual aids available for a clearer understanding of this concept? ...

Event for changing Ionic 2 page

Is there a way to execute code every time the page changes without adding an ngOnDestroy method to every page in Ionic 2? Instead of using Ionic 2 page lifecycle hooks like ionViewDidUnload, is there a simpler solution by adding a single method to the mai ...

Implementing dynamic class changes with *ngIf within a child component

Apologies if this question has been addressed before, I found two similar answers here: Question related | Close Solution An Angular Material Sidenav component contains three components. The parent component (highlighted in red) includes tab-like but ...

What are the best methods for identifying and handling transient upload errors in Azure blob storage?

I have a functional code for uploading files to Azure blob storage from frontend TypeScript. I need to handle errors that may occur during the upload process, such as network issues. How can we effectively catch and manage these errors on the client side ...

Loopback has a powerful access control feature that encompasses filtering capabilities

I have three models set up in Loopback: Reader, Book, and Note. The Reader model is essentially an instance of User and has the ability to log in. Here are the relationships between the models: Reader has many Books Reader has many Notes Book has many No ...