How to call component method from service? (angular2)

前端 未结 3 989
时光说笑
时光说笑 2020-11-30 01:18

I want to create service, which can interact with one component. All another components in my app, should be able to call this service, and this service should interact with

3条回答
  •  抹茶落季
    2020-11-30 02:05

    as this post is a bit old, I actualize the response of Tudor the stackblitz

    the service

    private customSubject = new Subject();
      customObservable = this.customSubject.asObservable();
    
      // Service message commands
      callComponentMethod(value:any) {
        this.customSubject.next(value);
      }
    

    the main-component

    constructor(private communicationService:CommunicationService){}
      ngOnInit()
      {
        this.communicationService.customObservable.subscribe((res) => {
              this.myFunction(res)
            }
          );
      }
      myFunction(res:any)
      {
        alert(res)
      }
    

    Another component that call to the method of the service

    constructor( private communicationService: CommunicationService  ) { }
    
      click() {
        this.communicationService.callComponentMethod("hello word");
      }
    

提交回复
热议问题