How to Pass Parameters to Angular 10|9 Service using @Inject

Last updated on by Digamber

In this tutorial, we will learn the easy and profound method to pass extra parameters to an Angular 10|9|8 service using @Inject decorator.

This comprehensive tutorial shade light on passing parameters to the Angular service through the angular dependency injection mechanism.

Injection tokens belong to Angular and permit the injection of values that don’t have a runtime representation. We can not inject everything like TypeScript; theoretically, it is not a JavaScript.

The injection tokens offer a robust and flexible way to connect to token value and permits that value to be injected into the component.

Angular Service Passing the Parameter Example

Let us try to understand it through the experimental paradigm; we have to create an Angular service and set up the parameter.

We are naming the parameter as paramId, it might seem a bit peculiar but facile to start with:

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

@Injectable({
  providedIn: 'root'
})

export class NgService {
    constructor (private paramId: string) { }
}

Here is the angular component where we can use the service that has the additional parameter.

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

@Component({
  selector: 'app-demo',
  template: `
    <div"> </div>
  `,
})

export class AppComponent {

  constructor() { }

}

Surely the next step is to pass the parameter (paramId) to the angular service.

Now, time has come to construct the injection token through the parameter with @Inject decorator.

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

@Injectable({
  providedIn: 'root'
})

export class NgService {
    constructor (
       @Inject('paramId') private paramId: string
    ) { }
}

Eventually, we can provide the token we created to the service via component’s providers’ array as mentioned below.

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

@Component({
  selector: 'app-demo',
  template: `
    <div"> </div>
  `,
   providers: [
    {provide: 'paramId', useValue: 'param-id'},
  ]
})

export class AppComponent {

  constructor(private ngService: NgService) { }

}

As you can see, we have narrowed the limitation of the provided paramId to this component with the token, if I want I can also use a different param in the other component.

So, finally, we have seen how to pass the extra parameter to the Angular 10 service easily.