'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.



Solution 1:[1]

You can achieve this using rxjs.

There's 'Subject' present which you can subscribe to in your component.

You create an 'Subject' in in service & subscribe to it in component's ngOninit

In the subscribe callback, call your component's method.

Please look at the mock example below:

Test.service.ts

import { Subject } from 'rxjs';

@Injectable({
providedIn: 'root',
})
export class TestService {

  // subscribe to this in component 
  triggerMethod = new Subject<any>();


  // this service method will trigger your component method
  serviceMethod( myCustomParam: any): void {
    this.triggerMethod.next(myCustomParam);
  }

}

MyComponent.ts


import { TestService } from 'test.service';

@Component({
    selector: 'my-component',
    templateUrl: './my-component.html',
    styleUrls: ['./my-component.scss'],
  })
  export class MyComponent implements OnInit {

    constructor(private testService: TestService) {};

    ngOninit() {
        this.testService.triggerMethod.subscribe(myCustomParam => {

            // call your method whenever its triggered.
            this.myMethod(myCustomParam)

        });
    }

    // your method
    myMethod(myParameter: string){
        ...
    }

  }

Make sure to unsubscribe it in the ngDestroy. Let me know if anythings unclear.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Waleed Ahmad