代表团:EventEmitter或Angular2观测 [英] Delegation: EventEmitter or Observable in Angular2

查看:999
本文介绍了代表团:EventEmitter或Angular2观测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现像在Angular2一个委托模式。
当用户点击一个导航项,我想调用一个函数,然后发出应该反过来由其他组件侦听事件处理的事件。

I am trying to implement something like a delegation pattern in Angular2. When the user clicks on a nav-item, I would like to call a function which then emits an event which should in turn be handled by some other component listening for the event.

下面是该方案:我有一个导航组件:

Here is the scenario: I have a Navigation component:

import {Component, Output, EventEmitter} from 'angular2/core';

@Component({
    // other properties left out for brevity
    events : ['navchange'], 
    template:`
      <div class="nav-item" (click)="selectedNavItem(1)"></div>
    `
})

export class Navigation {

    @Output() navchange: EventEmitter<number> = new EventEmitter();

    selectedNavItem(item: number) {
        console.log('selected nav item ' + item);
        this.navchange.emit(item)
    }

}

下面是观测部分:

export class ObservingComponent {

  // How do I observe the event ? 
  // <----------Observe/Register Event ?-------->

  public selectedNavItem(item: number) {
    console.log('item index changed!');
  }

}

关键问题是,如何让我的观测部分观察该事件?

The key question is, how do I make the observing component observe the event in question ?

推荐答案

<一个href=\"http://stackoverflow.com/questions/33380696/unable-to-figure-out-correct-eventemitter-or-observable-syntax-in-angular2-servi#comment54684990_33382275\">I've阅读的EventEmitter应仅用于组件发射的定制活动,而我们应该用接收的其他可观察/事件场景。 (参见<一个href=\"http://stackoverflow.com/questions/36076700/should-i-subscribe-manually-to-an-eventemitter/\">What是正确使用的EventEmitter的?)

I've read that EventEmitter should only be used for emitting custom Events in components, and that we should use Rx for other observable/event scenarios. (See also What is the proper use of an EventEmitter?)

所以,这里是一个使用可观察到的而不是EventEmitter 的实现。不像我EventEmitter实现,这个实现还存储当前选择的的NavItem 在服务上,从而创建一个观察组件时,它可以检索通过调用API的当前值的NavItem(),然后被通知通过变化的 navChange $ 观察到。

So, here's an implementation that uses an Observable instead of an EventEmitter. Unlike my EventEmitter implementation, this implementation also stores the currently selected navItem in the service, so that when an observing component is created, it can retrieve the current value via API call navItem(), and then be notified of changes via the navChange$ Observable.

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import {Observer} from 'rxjs/Observer';

export class NavService {
  private _navItem = 0;
  navChange$: Observable<number>;
  private _observer: Observer;
  constructor() {
    this.navChange$ = new Observable(observer =>
      this._observer = observer).share();
    // share() allows multiple subscribers
  }
  changeNav(number) {
    this._navItem = number;
    this._observer.next(number);
  }
  navItem() {
    return this._navItem;
  }
}

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number;
  subscription: any;
  constructor(private _navService:NavService) {}
  ngOnInit() {
    this.item = this._navService.navItem();
    this.subscription = this._navService.navChange$.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.changeNav(item);
  }
}

<大骨节病> Plunker

又见<一个href=\"https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service\"相对=nofollow>组件交互食谱例如,它使用了主题除了观测。虽然例子是家长和孩子的沟通,相同的技术适用于不相关的组件。

See also the Component Interaction Cookbook example, which uses a Subject in addition to observables. Although the example is "parent and children communication," the same technique is applicable for unrelated components.

这篇关于代表团:EventEmitter或Angular2观测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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