1

Can I listen to an event thrown in AngularJS in regular JS (Outside of angular?) I have a use case where I have an event being thrown using (rxjs) in Angular 2. Can I subscribe to that event outside in pure JS?

Here's some pseudo code I have

import {Observable} from 'rxjs/Rx';
...
 @Output() responsesEvt = new EventEmitter();
...
   this.responsesEvt.emit(this.form.value);

I want to subscribe to responsesEvt when it's fired outside of Angular 2.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user6123723
  • 10,546
  • 18
  • 67
  • 109
  • Please post code that demonstrates what you try to accomplish. What have you tried? Where did you fail? So you are talking about observables that emit values not DOM events? – Günter Zöchbauer Aug 09 '16 at 18:41
  • you can create your own observable and subscribe to it whenever you need, have you tried this ? – Pardeep Jain Aug 09 '16 at 18:47

2 Answers2

0

@Output() and EventEmitter is not supposed to be used for anything else than Angular event binding like (responsesEvt)="doSomething($event)". This works only from direct children to direct parents (doesn't bubble).

Otherwise use Observable or Subject.

If you want to notify JS outside of Angular just use DOM events like

constructor(private elRef:ElementRef, private renderer:Renderer) {}

someMethod() {
  this.renderer.invokeElementMethod(this.elRef.nativeElement, 
    'dispatchEvent', 
    [new CustomEvent('responses-evt', { bubbles: true })]);

See also https://stackoverflow.com/a/37875153/217408

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

you can create your own observable and subscribe to it whenever required like this:

import { Observable } from 'rxjs/Rx';
import * as Rx from 'rxjs/Rx';
.......

demo: Rx.Subject<any> = new Rx.Subject<any>();  //create new observable using subject
this.demo.next(your_value); //fire your observable
.......

in another file where you want to subscribe

this.Service.demo.subscribe(res => {  // subscribe your observable whenever any changes are there in your file
console.log(res);
})
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215