【Angular知识点】通过服务实现组件之间的通信EventEmitter

场景:界面是由多个组件组成的,如果组件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('收到了,我立马修改你的名字');
      }
    });
  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

smart_dream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值