angular2/4通过服务实现组件之间的通信EventEmitter ,emit(),subscribe()发射和接收.

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("收到了,我立马刷新列表");
           }
        });
    }

}

猜你喜欢

转载自blog.csdn.net/github_38281308/article/details/100526109