Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Compare switchMap() to nested subscribe calls.
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {ContactsService} from '../contacts.service';
import {Contact} from '../models/contact';
import 'rxjs/add/operator/switchMap';
import {Subscription} from 'rxjs';
selector: 'trm-contacts-detail',
templateUrl: './contacts-detail.component.html',
styleUrls: ['./contacts-detail.component.css']
export class ContactsDetailComponent implements OnInit {
subscription: Subscription;
contact: Contact;
constructor(private contactsService: ContactsService, private route: ActivatedRoute) {
* We need to subscribe to params changes because this component is
* reused when jumping between contacts. Hence ngOnInit isn't called
ngOnInit() {
this.subscription = this.route.params
.switchMap(params => this.contactsService.getContact(params['id']))
.subscribe(contact => = contact);
* This is the traditional nested approach to chaining async stream events.
* Notice the `clean()` function required to unsubscribe on errors and completion.
ngOnInit2() {
this.subscription = this.route.params.subscribe(params => {
let clean = () => restSub.unsubscribe();
let restSub = this.contactsService
.subscribe(contact => { = contact;
}, clean );
ngOnDestroy() {
Copy link

reggaeguitar commented Dec 13, 2018

This would be more helpful is you explained why clean is needed, other than that looks great.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment