the overloaded subscribe method takes three functions as args
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/Rx'; import { Observer } from 'rxjs/Observer'; @Component({ ... }) export class HomeComponent implements OnInit { myObservableSubscription: Subscription constructor() { } ngOnInit() { const myObservable = Observable.create((observer: Observer<string>) => { setTimeout(() => { observer.next('first package'); }, 2000); setTimeout(() => { observer.next('second package'); }, 4000); setTimeout(() => { observer.error('this does not work'); }, 5000); }); this.myObservableSubscription = myObservable.subscribe( (data: string) => { console.log(data); }, (error: string) => { console.log(error); }, () => { console.log('completed'); } ); } ngOnDestroy() { myObservableSubscription.unsubscribe(); } }a Subject is like an Observable but can be pushed to emit new data
in sample project first create a UsersService with a property of type Subject
a Subject is both an Observable and an Observer
import { Subject } from 'rxjs/Subject'; export class UsersService{ userActivated = new Subject(); }when a user is activated the handler calls the service'suserActivated Subject method next passing the id
... export class UserComponent implements OnInit { id: number; constructor(private route: ActivatedRoute, private usersService: UsersService) { } ... onActivate() { this.usersService.userActivated.next(this.id); } }another component subscribes to the service'suserActivated Subject
... export class AppComponent implements OnInit { user1Activated = false; user2Activated = false; constructor(private usersService: UsersService) { } ngOnInit() { this.usersService.userActivated.subscribe( (id: number) => { if (id === 1) { this.user1Activated = true; } if (id === 2) { this.user2Activated = true; } } ); } }every one second myNumbers observable changes based upon the chained map method
the subscription writes the value returned by the chained method
... export class HomeComponent implements OnDestroy, OnInit { myObservableSubscription: Subscription; myNumbersSubscription: Subscription; constructor() { } ngOnInit() { const myNumbers = Observable.interval(1000).map( (data: number) => { return data * -1; } ); this.myNumbersSubscription = myNumbers.subscribe( (number: number) => { console.log(number); } ); ... } ... }