Angular 2 事件广播

Angular 2 event broadcast

Angular 的新手 2. 我正在研究在同一级别组件之间广播事件。目前我知道 EventEmitter 只是可以将事件传递给上层组件。

我已经检查过这个 this link 并且知道 observable 可能是解决我的问题的一种方法,但是 url 中的示例似乎对我不起作用。

有谁知道如何将它(可观察的)用于广播事件或以其他方式将事件传输到同一级别的组件?

您只需要创建一些服务来发送您可以订阅的消息。可以是 Observable from rxjs, EventEmitter from node.js, or anything else that follows Observable pattern. Then you should use Dependency Injection to inject this service into concrete components. See this plunker.

class Broadcaster extends EventEmitter {}

@Component({
  selector: 'comp1',
  template: '<div>Generated number: {{ generatedNumber }}</div>',
})
class Comp1 {
  generatedNumber: number = 0;

  constructor(broadcaster: Broadcaster) {
    setInterval(() => {
      broadcaster.next(this.generatedNumber = Math.random());
    },1000);
  }
}

@Component({
  selector: 'comp2',
  template: '<div>Received number: {{ receivedNumber }}</div>',
})
class Comp2 {
  receivedNumber: number = 0;

  constructor(broadcaster: Broadcaster) {
    broadcaster.observer({
      next: generatedNumber => this.receivedNumber = generatedNumber
    });
  }
}

@Component({
  selector: 'app',
  viewProviders: [Broadcaster],
  directives: [Comp1, Comp2],
  template: `
    <comp1></comp1>
    <comp2></comp2>
  `
})
export class App {}

PS 在此示例中,我使用来自 angular2 的 EventEmitter,但同样,它可以是任何你想要的

使用BehaviorSubject

服务:

import { Injectable } from '@angular/core';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';    

@Injectable()
export class MyService {

   public mySubject: BehaviorSubject<number> = new BehaviorSubject<number>(0);


   public doSomething(): void { 
      let myValue: number = 123;
      this.mySubject.next(myValue);
   }
}

组件:

@Component({ 
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {

   constructor(private myService: MyService) { 
        this.myService.mySubject.subscribe(
             value => {
                console.log(value); 
             }
        );
   }

}