Search code examples
angulartypescriptangular-services

Is possible to get the Instance of an Angular Service outside an angular component?


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
   }
}

Solution

  • 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