The question does not ask the interaction with the component , it asks to call the component method from the service .
This can simply be achieved by implementing the service in the component. Then define a method inside the service that takes the function as a parameter. The method should save this function as a property of the service and call it where it wants.
// ------------------------------------------------------------------------------------- // codes for component import { JustAService} from '../justAService.service'; @Component({ selector: 'app-cute-little', templateUrl: './cute-little.component.html', styleUrls: ['./cute-little.component.css'] }) export class CuteLittleComponent implements OnInit { s: JustAService; a: number = 10; constructor(theService: JustAService) { this.s = theService; } ngOnInit() { this.s.onSomethingHappended(this.doThis.bind(this)); } doThis() { this.a++; console.log('yuppiiiii, ', this.a); } } // ------------------------------------------------------------------------------------- // codes for service @Injectable({ providedIn: 'root' }) export class JustAService { private myFunc: () => void; onSomethingHappended(fn: () => void) { this.myFunc = fn; // from now on, call myFunc wherever you want inside this service } }
source share