Angular 2 event broadcast

前端 未结 2 828
一个人的身影
一个人的身影 2020-12-15 20:19

New to Angular 2. I\'m working on broadcast a event between same level component. Currently I know EventEmitter just can transfer a event to upper level component.

I

2条回答
  •  有刺的猬
    2020-12-15 20:59

    Use BehaviorSubject

    Service:

    import { Injectable } from '@angular/core';
    import {BehaviorSubject} from 'rxjs/BehaviorSubject';    
    
    @Injectable()
    export class MyService {
    
       public mySubject: BehaviorSubject = new BehaviorSubject(0);
    
    
       public doSomething(): void { 
          let myValue: number = 123;
          this.mySubject.next(myValue);
       }
    }
    

    Component:

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

提交回复
热议问题