Vega
Vega

Reputation: 28708

How to inject a service in an exported function?

I wrote a 'popping' message (android toast like) component. All other components have it as a sibling and access it via a shared service. Now I would like to use it from an utility function too, like this one:

export function handleError(errorResp: Response | any): Observable<string> {
    ....
    // here I would like to display the message
    return Observable.throw(errMsg);
}

I thought I could pass the message service as parameter to handleError, but I feel it's not DRY, as I would need to make it from every component event though the component doesn't need it for other purposes. Could you give me some guidance?

Upvotes: 11

Views: 4183

Answers (2)

Lilit Mazmanyan
Lilit Mazmanyan

Reputation: 126

Depends on which Angular version you are using. Starting from Angular 15 release, a new approach has been introduced where dependencies can be injected using the inject function, instead of previous dependency injection mechanism.

The inject function provides a more flexible and dynamic way of handling dependencies within an Angular application, enabling developers to inject dependencies at runtime.

For more information please refer: https://blog.angular.io/angular-v15-is-now-available-df7be7f2f4c8

Upvotes: 0

Edmundo Santos
Edmundo Santos

Reputation: 8287

Since this function is outside your Angular app, there are no much options.

  • Pass it via argument, or
  • Directly import the service (via Javascript import, as the Angular's service is just a normal Javascript class), then use it. Note that it may not work depending on what requirements are necessary to instantiate the service (like if it uses some feature from Angular, or inject other services using DI), or
  • You could place your handleError function in another service that could get the Toast thing via Dependency Injection.

Upvotes: 2

Related Questions