Angular2 --- 通过服务实现组件之间的通信EventEmitter

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoxiong_jiaxin/article/details/83341722

场景:界面是由多个组件组成的,如果组件A中修改了数据内容,其他组件(与组件A中的数据有关联的)需要相应修改,那么就需要用到EventEmitter。

第一步:创建服务文件:emit.service.ts

import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class EmitService {
  public eventEmit: any;

  constructor() {
    // 定义发射事件
    this.eventEmit = new EventEmitter();
  }
}

第二步:配置模块:app.module.ts / app.component.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { EmitComonent } from './emit.component';
import { SubscribeComonent } from './subscribe.component';
import { EmitService } from './emit.service';

@NgModule({
  declarations: [
    AppComponent,
    EmitComonent,
    SubscribeComonent 
  ],
  imports: [
    BrowserModule.withServerTransition({appId: 'appId'})
  ],
  providers: [
    EmitService
  ],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule {}
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <event-emit></event-emit>
    <event-subscribe></event-subscribe>
  `
})
export class AppComponent {
  constructor() {}
}

第三步:在组件中发射消息:emit.component.ts

import { Component } from '@angular/core';
import { EmitService } from './emit.service';

@Component({
  selector: 'event-emit',
  templateUrl: './emit.component.html'
})
export class EmitComponent {
  constructor(public emitService: EmitService) {}

  emitFun() {
    // 如果组件中,修改了某些数据,该数据在其他组件中有关联,那么就可以发射一个字符串过去
    // 对方接收到这个字符串比对一下,刷新数据。
    this.emitService.eventEmit.emit('changeYourName');
  }
}

第四步:在组件中接收消息:subscribe.component.ts

import { Component, OnInit } from '@angular/core';
import { EmitService } from './emit.service';

@Component({
  selector: 'event-subscribe',
  templateUrl: './subscribe.component.html'
})
export class SubscribeComonent implements OnInit {
  constructor(public emitService: EmitService) {}

  ngOnInit() {
    // 接收发射过来的数据
    this.emitService.eventEmit.subscribe((value: any) => {
      if (value == 'changeYourName') {
        // 这里就可以操作数据
        alert('收到了,我立马修改你的名字');
      }
    });
  }

}

猜你喜欢

转载自blog.csdn.net/xiaoxiong_jiaxin/article/details/83341722