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

时光总嘲笑我的痴心妄想 提交于 2019-11-27 15:47:52

I agree that your idea regarding a service with an observable is your best option here (as others have suggested) - although I'd prefer a BehaviorSubject in this case. Here's a simple, working plunkr demonstrating how you could implement this:

https://plnkr.co/edit/quHc2yOkxXIbXYUlnZbB?p=preview

If we break down the requirement, what you need here is an Event Proxy service that just passes on the event. This plunkr is also able to also pass a parameter object via the service - in case you need to do this - but if not then just pass any object you want (or just remove the param arguments from all the methods entirely).

This implementation doesnt care that the components are not siblings - because we're using a service. Both will be provided with the same service instance regardless of the structure of your app.

For quick reference, here are the pieces of code that matter:

EventProxyService

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class EventProxyService {

 private eventSubject = new BehaviorSubject<any>(undefined);

 triggerSomeEvent(param: any) {
     this.eventSubject.next(param);
 }

 getEventSubject(): BehaviorSubject<any> {
    return this.eventSubject;
 }
}

FirstComponent

import { Component, OnInit } from '@angular/core';
import { EventProxyService } from './event-proxy.service';

@Component({
  selector: 'app-first',
  templateUrl: './src/first.component.html'
})
export class FirstComponent implements OnInit {
  displayText = 'I havent created any events yet.';
  constructor(private eventProxyService: EventProxyService) { }

  ngOnInit() { }

  triggerAnEvent() {
    this.eventProxyService.triggerSomeEvent(Date());
    this.displayText = 'I fired an event.'
  }
}

SecondComponent

import { Component, OnInit } from '@angular/core';
import { EventProxyService } from './event-proxy.service';

@Component({
  selector: 'app-second',
  templateUrl: './src/second.component.html'
})
export class SecondComponent implements OnInit {

  displayText = 'I havent got an event yet';
  constructor(private eventProxyService: EventProxyService) { }

  ngOnInit() {
    this.eventProxyService.getEventSubject().subscribe((param: any) => {
      if (param !== undefined) {
        this.theTargetMethod(param);
      }
      });
  }

  theTargetMethod(param) {
    this.displayText = 'Target Method got called with parameter: "' + param + '"';
  }
}

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<any>();
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;
      ....
   }
}

Depending on what you are trying to do, you have two options.

First: If you need Angular features (e.g. dependency injection) or want to share data, you should think about using a service. There is enough of documentation and tutorials already (see angular docs.) I recommend reading this thoroughly.

Second: In case you just need JavaScript capabilities, you could create a TypeScript file (e.g. /src/app/shared/tools.ts and put your method there. This is mostly useful for static functions that do some kind of calculations, formatting or similar. You can then import and use the function wherever you need it. (Tip: make it pure.)

Inheritance the components.

Let's say one component.

@Component({
...
})
export class Component1 {
  constructor();

  public test1() {
    console.log("this is a test");
  }
}

you can inheritance the first component as a child an execute the test1 method

@Component({
...
})

export Class Component2 extends Component1 {
  constructor();

  //Execute test1 method
  test1();
}

Also, remember that if you are using angular you need to export your components in the declarations and entryComponents. Also you need to import it in your new component.

import { Component1 } from 'directory/component';

/* Example */

import { SplashScreen } from 'directory/splash-screen';

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!