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?
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.
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.
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.
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.
Since this function is outside your Angular app, there are no much options.
handleError
function in another service that could get the Toast thing via Dependency Injection.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With