Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a service in an exported function?

Tags:

angular

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?

like image 278
Vega Avatar asked Jul 11 '17 10:07

Vega


People also ask

Can we use service without injectable?

If you want to use angular services (and Http is an angular service) you must inject them as I told above as a constructor attribute to another service / component , which means if you want to use Http you need to have your service injectable. So the answer is no, you can't do it in a nice way.

What mechanism is used to use a service in a component?

Services are wired together using a mechanism known as Dependency Injection (DI). We just need to have an injectable service class to be able to share these service methods to any consuming component. Also, DI in our Angular components/services can be implemented using either constructor or injector.

What is service and Dependency Injection in Angular?

Dependency injection (DI) is the part of the Angular framework that provides components with access to services and other resources. Angular provides the ability for you to inject a service into a component to give that component access to the service.

What is Angular injector?

Injectors are data structures that store instructions detailing where and how services form. They act as intermediaries within the Angular DI system. Module, directive, and component classes contain metadata specific to injectors. A new injector instance accompanies every one of these classes.


1 Answers

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.
like image 147
Edmundo Rodrigues Avatar answered Oct 06 '22 12:10

Edmundo Rodrigues