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?;
      }
}
Jayesh
  • 641
  • 4
  • 13
  • 32

1 Answers1

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);
  }
}
Daniel
  • 10,641
  • 12
  • 47
  • 85