5

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();
  }
}
bhagat
  • 153
  • 1
  • 11
  • 4
    Make `MyUtilClass` @Injectable() the same way you are doing with `MyServcie` – Antoniossss Nov 06 '18 at 12:05
  • 1
    The same way you would any other service as services can be injected into each other. – Igor Nov 06 '18 at 12:05
  • Possible duplicate of [Angular 2: Inject Service to another service. (No provider error)](https://stackoverflow.com/questions/37152608/angular-2-inject-service-to-another-service-no-provider-error) – Igor Nov 06 '18 at 12:09
  • we don't need to add @Injectable decorator if we add the MyUtilClass to providers list , right ? unless we use providedIn – Muhammed Albarmavi Nov 06 '18 at 12:23

3 Answers3

4

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!

Saad Maqbool
  • 301
  • 2
  • 10
3

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

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
-1

You can create file e.g. util.ts with your utils and export functions included directly e.g.

export function do() {
  //do something
}

next it may be imported and used into your service. In the other hand instead of class you can create MyUtilService and provide it into your MyService what is Angular recommended way.