1

I'm using ionic2, I implemented a class:

import {EventEmitter, Injectable} from 'angular2/core';
@Injectable()
export class LocalPushClear extends EventEmitter<number> {
    constructor() {
      super();
    }
}

The class is used by on of my components to connect cordova plugin event to another component which subscribe to LocalPushClear, I listen to clear events, ones it fires, I emit using LocalPushClear and some other component subscribes:

this._LocalPushClear.subscribe(data => {
    // Some action is taken here
});

The thing is that, I was expecting automatic change detection to be executed upon subscription callback execution(when its done), but it seems like there is no change detection execution at all, I have to do something like click a button or wrap my Some action with zone.run, I'm not sure if its a valid behavior or maybe I'm doing something wrong.

Edit: I traces the code and it leads to Subject, so its basically custom event emitter that angular NgZone don't know about(at least I think), but I'm sure, if anyone could confirm, maybe future explain I will be very thankful.

Aviel Fedida
  • 4,004
  • 9
  • 54
  • 88
  • Seems to me that your **Some Action** manipulates some properties within the same component that has subscribed to `LocalPushClear`, at least that's what i understood from mentioning the change detection issue. If this is the case, then yes it's required to wrap the **Some Action** with `zone.run` as the change request comes from outside of component domain. –  May 02 '16 at 22:35
  • @Hani first, thanks for the comment, the thing that bugs me is that its `EventEmitter` that I'm using, exported from 'angular/core', I think when I subscribe there should already be a change detection activation within the code that implement it, I'm looking for direct answer, something like "EventEmitter that you export from angular/core won't automatically run change detection" or maybe I'm doing something wrong. – Aviel Fedida May 02 '16 at 22:59

1 Answers1

2

You definitely should not extend EventEmitter. EventEmitter is only supposed to be used for @Output()s. Just use a Subject instead.

Angular doesn't get notified about values emitted by EventEmitter (when used this way) or Subject. Normally the code that causes the Observable (Subject) to emit new values is executed by code that causes change detection when completed for example when called from an event handler or setTimeout.

In your case the cause seems to be that the code that emits new values using LocalPushClear runs outside Angulars zone.

You can use one of the methods explained in https://stackoverflow.com/a/34829089/217408 to trigger change detection after the Observable emits an event.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567