Home > database >  Angular: trigger component method from service
Angular: trigger component method from service

Time:03-04

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related