1

Is possible to get the instance reference of a Injectable angular service in a generic class? I need to not put the angular Injectable in the constructor, so I am trying to find a different approach to get the Service reference.

Example:

export class Utils {
  getData(): string {
      //Service reference without using the constructor
      if(!isAuthorized()) return

     //Do something
  }
}



@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
  isAuthorized(): boolean {
      //Do stuff
   }
}
Swampy469
  • 63
  • 4
  • this could help: https://stackoverflow.com/questions/41432388/how-to-inject-service-into-class-not-component – TommyR22 Jul 27 '22 at 09:11

1 Answers1

2

As of Angular 14, inject(..) can be used in a wider (but still limited) set of situations:


export class Utils {
  authenticationService = inject(AuthenticationService);

  getData(): string {
    if(!authenticationService.isAuthorized()) return;

    //Do something
  }
}

https://angular.io/api/core/inject#usage-notes

https://netbasal.com/unleash-the-power-of-di-functions-in-angular-2eb9f2697d66

wlf
  • 3,086
  • 1
  • 19
  • 29