How to execute a function from another component that is NOT a sibling of the first component?

后端 未结 4 1594
长情又很酷
长情又很酷 2020-12-04 00:06

I\'m trying to execute a function from another component (These 2 components are NOT siblings). My guess is that I will need to use @Output and even

4条回答
  •  孤城傲影
    2020-12-04 00:44

    Use a service. Subscribe to a Observable of the service in your home.component and execute a change in the observable from tools

    //Your service
    private dataSource = new Subject();
    data = this.searchDataSource.asObservable();
    change(param:any) {
       this.searchDataSource.next(param)
    }
    //Your home.component
    this.myService.data.subscribe((param: any) => {
          console.log(param)
    }
    //Your tool
    this.myService.change("Hello world");
    

    As the question is execute a function, you can use this idea, doing some like

    //Your tool:
        this.myService.change("Command1") 
    //or even
        this.myService.change({"command":"Command1","arg":myvariable})
    
    //Your home.component
    this.myService.data.subscribe((param:any)=>
    {  switch (param.command)
       {
          case "Command1":
              this.function1(param.arg);
              break;
          case "Command2":
              this.function2();
              break;
          ....
       }
    }
    

提交回复
热议问题