如何在 Angular2 中订阅服务上的事件? [英] How to subscribe to an event on a service in Angular2?

查看:28
本文介绍了如何在 Angular2 中订阅服务上的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用 EventEmitter 引发事件.如果我有这样的组件,我还可以附加一个要调用的方法:

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:

<component-with-event (myevent)="mymethod($event)" />

当我有这样的组件时,一切都很好.我将一些逻辑移到服务中,我需要从服务内部引发一个事件.我所做的是这样的:

When I have a component like this, everything works great. I moved some logic into a service and I need to raise an event from inside the Service. What I did was this:

export class MyService {
  myevent: EventEmitter = new EventEmitter();

  someMethodThatWillRaiseEvent() {
    this.myevent.next({data: 'fun'});
  }
}

我有一个组件需要根据此事件更新一些值,但我似乎无法让它工作.我试过的是这样的:

I have a component that needs to update some value based on this event but i can't seem to make it work. What I tried was this:

//Annotations...
export class MyComponent {
  constructor(myService: MyService) {
    //myService is injected properly and i already use methods/shared data on this.
    myService.myevent.on(... // 'on' is not a method <-- not working
    myService.myevent.subscribe(.. // subscribe is not a method <-- not working
  }
}

当引发它的服务不是组件时,如何让 MyComponent 订阅该事件?

How do i make MyComponent subscribe to the event when the service that raises it is not a component?

我在 2.0.0-alpha.28 上

I'm on On 2.0.0-alpha.28

修改我的工作示例"以使其实际工作,因此可以将重点放在不工作的部分;)

Modified my "working example" to actually work, so focus can be put on the not-working part ;)

示例代码:http://plnkr.co/edit/m1x62WoCHpKtx0uLNsIv

推荐答案

更新:我找到了使用 BehaviorSubject 或 Observable 而不是 EventEmitter 来解决这个问题的更好/正确的方法.请参阅此答案:https://stackoverflow.com/a/35568924/215945

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

此外,Angular 文档现在有一个 使用主题的食谱示例.

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

原始/过时/错误答案:再次不要在服务中使用 EventEmitter.这是一种反模式.

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

使用 beta.1... NavService 包含 EventEmiter.组件导航通过服务发出事件,组件 ObservingComponent 订阅事件.

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

nav.service.ts

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

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

这篇关于如何在 Angular2 中订阅服务上的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆