角度2.如何在不同级别的组件之间进行交互? [英] Angular 2. How interact between different level components?

查看:66
本文介绍了角度2.如何在不同级别的组件之间进行交互?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,有很多方法可以在父级-子级和子级-父级组件之间进行交互,例如EventEmitter.但是,除了为此目的使用Service之外,还有什么方法可以在不是父子关系或子父母关系的组件之间进行交互?

As far as I know there is numerous ways to interact between parent - child and child - parent components, like EventEmitter for example. But is there any way to interact between components that are not parent - child or child -parent relations, different from using Service for this purpose?

推荐答案

使用此类

import { EventEmitter, Injectable } from "@angular/core";
@Injectable()
export class SharedService {
  private emitter: EventEmitter<any>;
  constructor() {
    this.emitter = new EventEmitter<any>();
  }
  getEmitter(): EventEmitter<any> {
    return this.emitter;
  }
  emit(data: any): void {
    this.emitter.emit(data);
  }
}

并订阅诸如

@Component({
 template: ''
})
export class MyComponent{
 constructor(private emitter: SharedService){
   this.emitter.getEmitter().subscribe(e => {
    // do stuff here
   });
 }
}

别忘了将其添加到NgModule并将其用作类似服务.

dont forget to add it to NgModule and use it as like services.

这篇关于角度2.如何在不同级别的组件之间进行交互?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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