angular2/4通过服务实现组件之间的通信EventEmitter

139 篇文章 0 订阅
原文出处: https://segmentfault.com/a/1190000011425280

之前的文章讲过组件和组件之间的通信,使用@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()发射和接收;


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值