Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create RxJS subject in Angular 2?

Tags:

angular

rxjs

I am able to create an Observable in my angular component in below mentioned way

...
...
import { Observable } from 'rxjs/Observable';
..
...
let observable = new Observable( function subscribe(observer) {
        observer.next(1);
        observer.next(2);
        observer.next(3);
        observer.next(4);
        setTimeout(() => {observer.next(5); },9000);
    });

But am not aware of how to create a Subject , can some one provide an example for the same ?

like image 831
refactor Avatar asked Nov 05 '16 14:11

refactor


2 Answers

Here's a plunker: http://plnkr.co/edit/jLtFLjWrvHGI0ZPHl10B?p=preview

import {Subject} from 'rxjs/Subject'; // from 'rxjs'; for the newer rxjs versions

@Injectable()
export class MyService {

    public invokeEvent:Subject<any> = new Subject();
    
    constructor() {}
}

subscribe to it like an observable:

  constructor(private _myService: MyService) {
         this._myService.invokeEvent.subscribe((value) => {
           console.log(value); 
         });
       }

and push values to it like an observable again with next

  ngAfterViewInit(){
      this._myService.invokeEvent.next(1);
  }
like image 76
eko Avatar answered Nov 14 '22 14:11

eko


Using Rx.Subject with Angular it is no different from using it without Angular, the main principle is the same, look at the example below

const subject = new Rx.Subject();
const subscription = subject.subscribe(
  (data) => console.log(data),
  (err) => console.log(err),
  () => console.log('Completed')
);

subject.next(1);
subject.next(2);
subject.next(3);
subject.complete();
<script src="https://unpkg.com/@reactivex/[email protected]/dist/global/Rx.umd.js"></script>

You need to make new instance Rx.Subject, then subscribe to it where you need to, and fire event.

like image 33
Oleksandr T. Avatar answered Nov 14 '22 13:11

Oleksandr T.