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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

And the constructor of Utils class must itself be callled from the injection context (e.g. component field initializer)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.