Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject class into Service [Angular 6]

Can we make a class(not service) as shared utility which can be injected into services or even components through angular dependency injection?

MyUtilClass

export class MyUtilClass{

  do(){
     // something
  }
}

MyService

export class MyService{
  constructor(private uitl:MyUtilClass){
    util.do();
  }
}
like image 252
bhagat Avatar asked Nov 06 '18 12:11

bhagat


People also ask

How do you inject service in Angular?

The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.

How do I pass a parameter to a service in Angular 6?

If you want to pass additional parameters to an Angular service, what you are looking for is @Inject decorator. It helps you pass your parameters to the service through Angular's dependency injection mechanism. @Inject() is a manual mechanism for letting Angular know that a parameter must be injected.

What is the use of injecting services in component class?

As mentioned, services are implemented using dependency injection. The service class is imported into the component. ts file. The main reason for doing this is to tell Angular that when the component is created, an instance of the service class is also created to perform all the tasks.


2 Answers

Services are classes with a bit addition difference(not structurally), they has a decorator @Injectable() not more! And you can make service through angular CLI by running

ng generate service service-name

it will be injected in your other class.enjoy!

like image 137
Saad Maqbool Avatar answered Nov 06 '22 22:11

Saad Maqbool


Service in angular is just a class so you can inject any class to any class

Utility

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

@Injectable({providedIn:'root'})
export class Utility {
  constructor(){
    console.log('Utility is created');
  }
}

MyServiceService

import { Injectable } from '@angular/core';
import {Utility} from './utility'

@Injectable({providedIn:'root'})
export class MyServiceService {

  constructor(private uitl:Utility) { }

}

{providedIn:'root'} in a feature in angular 6 another way is to add MyServiceService , Utility to providers array in app.module.ts in that case you can remove @Injectable decorator in Utility class

demo - check the console

like image 3
Muhammed Albarmavi Avatar answered Nov 06 '22 22:11

Muhammed Albarmavi