angular2/4經過服務實現組件之間的通訊EventEmitter

以前的文章講過組件和組件之間的通訊,使用@Output @Input,侷限,若是組件嵌套層次比較深,那麼就很麻煩了。以前文章地址:https://segmentfault.com/a/11...css

注意:如今的場景是這樣的,界面是由N多個組件組成的,若是一個組件中修改了接口的內容,其餘組件須要調接口刷新數據,那麼就用到了EventEmitterhtml

一、建立服務,new一個EventEmitterbootstrap

import {Injectable, EventEmitter, OnInit} from "@angular/core";
@Injectable()
export class EmitService implements OnInit {
    public eventEmit: any;

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

    ngOnInit() {

    }
}

二、配置module.tssegmentfault

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 {
}

三、定義組件,發射消息app

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");
    }
}

四、定義接收組件,接收比對發射的字符串,判斷,調取接口,刷新組件內容ide

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()發射和接收;this

相關文章
相關標籤/搜索