You usually want to separate the service logic from the usage.
My suggestion is to save a Subject
(or BehaviorSubject
, depends on the usage of the service) in the service,
and have the parent
component next
it, and the child
component will subscribe to that Observable
(every Subject
is an observable, you can use Subject.toObservable
when returning it to make sure you don't give the Subject
in the API).
I have a great example to give out.
I'm currently working on a project that has a canvas
that receives keyboard input from window
, and also, I have a chat in the same page. Before the fix I'm about to explain to you, whenever I pressed any of WASD
in the chat, it would cause the canvas to receive the input (effectively moving the character).
What I wanted to do, is to intercept input whenever I'm in the chat.
I have a service, called GameInputDisableService, which is responsible for the interception. It saves a BehaviorSubject
, which is initialized to false
.
I have the MessageInputComponent
(TS, HTML), where I inject the service in the TS, and call the service methods in the input's focus
and focusout
events.
On the other end, I have the AioGameComponent
(TS), which has an @Input() disableInput: boolean
, the component which wraps this component transfers the value saved in GameInputDisableService
to the AioGameComponent
I hope this works for you, sounds like this kind of service can help you.
The difference is that you might want to subscribe to the observable and call your compnent's method, instead of transferring the value in an @Input
to the child component