angular 4: call a method from a different component

后端 未结 2 625

I have 2 sibling components, I am doing an http request in one component, and if a particular condition happens, it should make another http request, written in another comp

2条回答
  •  囚心锁ツ
    2020-12-31 20:29

    You have 2 issues to address.

    The first is that if you want to use Dependency Injection, your components need to have a parent-child relationship. So, in your case, if InputFieldComponent is a child of SendCardComponent, then you can use simple (constructor) dependency injection to get an instance of the parent SendCardComponent from the InputFieldComponent.

    And that brings us to the second issue - the implementation. If I wanted to do the above, then I'd end up with:

    export class InputFieldComponent implements OnInit {
    
      value = '';
      output = '';
    
      constructor(private http : Http, private saro: SendCardComponent) { }
    
      onEnter(value: string) { 
    
        this.value = value;
        this.saro.methodOnSendCardComponent();  
        ......
    

    If the other relationship existed - where InputFieldComponent is a parent of SendCardComponent, then you can use @ViewChild to get your instance of SendCardComponent from InputFieldComponent.

    However, as noted, both of the above methods require you to change your view hierarchy. If the two components NEED to stay as siblings, then neither of the above would work.

    Thinking it through further though, if you only need access to SendCardComponent to use logic (i.e. methods) from it, why not abstract that logic to a service, and then you can use that service anywhere in your hierarchy? This bypasses your present problem quite neatly, and is sound advice in general. Honestly, your components should focus their behaviour on higher level concerns and 'outsource' as much as they reasonably can to services anyway.

提交回复
热议问题