如何从不是第一个组件的同级组件的另一个组件执行功能? [英] How to execute a function from another component that is NOT a sibling of the first component?

查看:103
本文介绍了如何从不是第一个组件的同级组件的另一个组件执行功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从另一个组件执行功能(这2个组件不是同级).我的猜测是,我将需要使用 @Output和eventEmitter 来完成此操作或创建 Service 并订阅 Observable 来共享相同的内容所有组件中的数据(我知道如何传递消息(字符串),但我不知道如何执行功能).我不太确定从哪里开始.我正在尝试从 function2 执行 function1 .谁能帮我解决这个问题? 请提供一个小矮人.这是我的项目的样子:

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 eventEmitter to accomplish this or create a Service and subscribe to the Observable to share the same data throughout all the components (I know how to pass a message( string) but I don't know how to execute a function). I'm not really sure where to start. I'm trying to execute function1 FROM function2. Can anyone help me on how to get this to work? Please provide a plunker. This is what my project looks like:

   src
   |__app(FOLDER)
      |__home(FOLDER)
      |     |
      |     |__home.component.ts 
      |                  |______function2(){
      |                          What do I need to put in here to execute function1?
      |                          }
      | 
      |__products(FOLDER) 
           |
           |__tools(FOLDER)
                  |
                  |____tools.component.ts
                                   |____function1(){
                                         alert("I'm inside function 1!!");
                                         }

如您所见,我有一个具有功能2的文件 home.component.ts 和一个具有功能1的文件 tools.component.ts ,因此,有关如何执行的任何想法来自function2的function1吗?

As you saw I have a file home.component.ts that has function2 and a file tools.component.ts that has function1, so any ideas how to execute function1 from function2 ?

推荐答案

我同意您关于具有可观察性的服务的想法是您最好的选择(正如其他人所建议的那样)-尽管我更喜欢在其中使用BehaviorSubject这个案例.这是一个简单而有效的plunkr,演示了如何实现此目标:

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

如果我们分解要求,那么您需要的是仅传递事件的事件代理服务.该plunkr还能够通过服务传递参数对象(以防您需要这样做),但如果不这样做,则只需传递您想要的任何对象(或从所有方法中完全删除param参数).

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.'
  }
}

次要组件

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 + '"';
  }
}

这篇关于如何从不是第一个组件的同级组件的另一个组件执行功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆