0

Is there any option to execute method in a component from a service directly?

@Component({
  selector:'component'
})
export class Component{
  function2(id){ 
    console.log('ID printed '+ id);
  }
}


@Injectable()

export class Service {
  callfunction2() {
    //how?;
      }
}
4
  • 4
    No, because that would be the opposite of how components and services should interact (components should call services, not vice-versa). Commented May 30, 2019 at 15:43
  • 1
    Technically it is possible with injectors, but don't do it (for the reasons listed in the comment above) Commented May 30, 2019 at 15:43
  • any alternative solution ??? Commented May 30, 2019 at 15:45
  • Possible duplicate of Angular service call function in component Commented May 30, 2019 at 15:49

1 Answer 1

1

You shouldn't call a component function from a service.

You could however create a Subject in the service, and subscribe to it from the component.

In that case once callfunction2 is passed, it emits the id value on the Subject, and any components that subscribe to this Subject will receive the value

@Component({
  selector:'component'
})
export class Component{

  constructor(private service: Service) {}

  function2(id){
    this.service.subject.subscribe(id => {
        console.log('ID printed ' + id);
    });
  }
}


@Injectable()

export class Service {

  public subject: Subject<any> = new Subject<any>();

  callfunction2(id) {
    this.subject.next(id);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.