angular2/4通过服务实现组件之间的通信EventEmitter
发布时间:2020-12-17 08:44:27 所属栏目:安全 来源:网络整理
导读:之前的文章讲过组件和组件之间的通信,使用@Output @Input,局限,如果组件嵌套层次比较深,那么就很麻烦了。之前文章地址:https://segmentfault.com/a/11... 注意:现在的场景是这样的,界面是由N多个组件组成的,如果一个组件中修改了接口的内容,其他组件
之前的文章讲过组件和组件之间的通信,使用@Output @Input,局限,如果组件嵌套层次比较深,那么就很麻烦了。之前文章地址:https://segmentfault.com/a/11... 注意:现在的场景是这样的,界面是由N多个组件组成的,如果一个组件中修改了接口的内容,其他组件需要调接口刷新数据,那么就用到了EventEmitter 1、创建服务,new一个EventEmitter import {Injectable,EventEmitter,OnInit} from "@angular/core"; @Injectable() export class EmitService implements OnInit { public eventEmit: any; constructor() { // 定义发射事件 this.eventEmit = new EventEmitter(); } ngOnInit() { } } 2、配置module.ts import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppComponent} from './app.component'; import {EmitComonent} from "./emit.component"; import {EmitService} from "./emit.service"; @NgModule({ declarations: [ AppComponent,EmitComonent ],imports: [ BrowserModule ],providers: [ EmitService ],bootstrap: [ AppComponent ] }) export class AppModule { } 3、定义组件,发射消息 import {Component} from '@angular/core'; import {EmitService} from "./emit.service" @Component({ selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(public emitService: EmitService) { } emitFun() { // 如果组件中,修改了某些数据,需要刷新用用户列表,用户列表在其他组件中,那么就可以发射一个字符串过去,那边接收到这个字符串比对一下,刷新列表。 this.emitService.eventEmit.emit("userList"); } } 4、定义接收组件,接收比对发射的字符串,判断,调取接口,刷新组件内容 import {Component,OnInit} from "@angular/core"; import {EmitService} from "./emit.service" @Component({ selector: "event-emit",templateUrl: "./emit.component.html" }) export class EmitComonent implements OnInit { constructor(public emitService: EmitService) { } ngOnInit() { // 接收发射过来的数据 this.emitService.eventEmit.subscribe((value: any) => { if(value == "userList") { // 这里就可以调取接口,刷新userList列表数据 alert("收到了,我立马刷新列表"); } }); } } 总结:其实就是EventEmitter的两个方法,emit(),subscribe()发射和接收; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |