Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular: trigger component method from service

I am trying to trigger component method with parameter from service.

Lets say I have component
myComponent.ts

myMethod(myParameter: string){
   ...
}

How can i trigger that method with custom parameter from service? I know its not best practice.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The approach you have described is distinctly "un-Angular". Services don’t call methods on components.

As mentioned in the comments on your post, the "correct" way of achieving the behaviour you want (component reacts to change in service) is to use an Observable.

Your service will expose some form of Observable-like stream (Observable, Subject, BehaviorSubject) and the component will subscribe to it in order to react to its emissions.

Yes it’s "more difficult", but it’s the best practice and the only clean way of achieving what you’re looking for.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading