0

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.

4
  • You can use Subject or BehaviorSubject to achieve that. Commented Mar 4, 2022 at 8:48
  • I would say "dont do that" Commented Mar 4, 2022 at 8:48
  • If it is an reaction to component calling a method - maybe a callback. Otherwise, subscribe to observabe stream - which is a good practice Commented Mar 4, 2022 at 8:49
  • It isn't so much a question of "best practice", rather going against the way Angular works. Components and classes are essentially Typescript classes. You could import one to another, create an object of it, and call all the public scoped methods on it. But your object of the component in the service is not the one Angular render engine created, so whatever you do this way wouldn't be reflected in the DOM. Easier way is to create a hot observable in the service, subscribe to it the component, emit the value from service, and in it's callback trigger the this.myMethod(someValue). Commented Mar 4, 2022 at 8:58

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

Hi Waleed, great well-detailed answer. I'd suggest not using subscribe callbacks and using pipeable operators instead. They do a better job of enforcing better practices.
Thanks WIll. I'm new to pipeable operators & having a bit of trouble understanding it, Would be great if you can briefly describe what changes to be made to convert this example into your method.
There are a fair number to know about :) I suggest learnrxjs.io as a great resource. In this specific case, calling the method is a side effect (i.e. it depends on an Observable emission without modifying it in anyway), so you'd use tap.
Thanks, I'll definitely look into it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.