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

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

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

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

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

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

//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的服务不是组件时,如何让MyComponent订阅该事件?

我在2.0.0-alpha上.28

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

示例代码:

推荐答案

Update:我找到了一个更好/正确的方法来解决这个问题,使用行为主体或可观察对象,而不是事件emits 器.请看这个答案:https://stackoverflow.com/a/35568924/215945

另外,角形doctor 现在有cookbook example that uses a Subject分.


Original/outdated/wrong answer:还是don't use an EventEmitter in a service.这是一种反模式.

使用测试版.1.NavService包含EventEmitter.组件导航通过服务发出事件,组件观察组件订阅事件.

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

组件.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

Angular相关问答推荐

Angular独立组件(使用LoadComponents)-懒惰加载服务不工作

Angular 服务错误处理响应类型=BLOB

天使17中的倒计时器

Angular 17水化-POST请求同时触发客户端/服务器端,而GET请求仅触发服务器端?

P-DropDown不会使用react 式表单手动设置Value

如何在独立应用程序中全局禁用基于媒体查询的Angular 动画?

MAT折叠面板的动态开启和关闭无法工作

等待两个订阅完成而不嵌套

如何在对话框angular material内对齐按钮?

可从 Angular2 中的

Angular 5 国际化

由router-outlet 创建时如何将css类应用于组件元素?

未绑定断点 - VS Code | Chrome | Angular

Angular2 中的providers提供者是什么意思?

Angular 2 - 组件内的 formControlName

在 Angular 2 中打印 Html 模板

Angular 2中不同页面的多种布局

提交后在Angular 2中重置表单

如何升级 Angular CLI 项目?

ngClass 中的多个条件 - Angular 4