How to subscribe to an event on a service in Angular2?

前端 未结 2 2021
情歌与酒
情歌与酒 2020-11-28 02:27

I know how to raise an event with the EventEmitter. I can also attach a method to be called if I have a component like this:



        
相关标签:
2条回答
  • 2020-11-28 02:36

    Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945

    Also, the Angular docs now have a cookbook example that uses a Subject.


    Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.

    Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.

    nav.service.ts

    import {EventEmitter} from 'angular2/core';
    export class NavService {
      navchange: EventEmitter<number> = new EventEmitter();
      constructor() {}
      emitNavChangeEvent(number) {
        this.navchange.emit(number);
      }
      getNavChangeEmitter() {
        return this.navchange;
      }
    }
    

    components.ts

    import {Component} from 'angular2/core';
    import {NavService} from '../services/NavService';
    
    @Component({
      selector: 'obs-comp',
      template: `obs component, item: {{item}}`
    })
    export class ObservingComponent {
      item: number = 0;
      subscription: any;
      constructor(private navService:NavService) {}
      ngOnInit() {
        this.subscription = this.navService.getNavChangeEmitter()
          .subscribe(item => this.selectedNavItem(item));
      }
      selectedNavItem(item: number) {
        this.item = item;
      }
      ngOnDestroy() {
        this.subscription.unsubscribe();
      }
    }
    
    @Component({
      selector: 'my-nav',
      template:`
        <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
        <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
      `,
    })
    export class Navigation {
      item = 1;
      constructor(private navService:NavService) {}
      selectedNavItem(item: number) {
        console.log('selected nav item ' + item);
        this.navService.emitNavChangeEvent(item);
      }
    }
    

    Plunker

    0 讨论(0)
  • 2020-11-28 02:38

    Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

    0 讨论(0)
提交回复
热议问题