Skip to content

Instantly share code, notes, and snippets.

@armanozak
Last active April 15, 2021 06:46
Show Gist options
  • Save armanozak/18ff9b818d2bd3a81e8657599ab3b925 to your computer and use it in GitHub Desktop.
Save armanozak/18ff9b818d2bd3a81e8657599ab3b925 to your computer and use it in GitHub Desktop.
[Angular Reactivity Streamlined] Clearing RxJS subscriptions in an Angular component #blog #angular #rxjs
import { Component, OnDestroy } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Subscription } from "rxjs";
import { map, withLatestFrom } from "rxjs/operators";
@Component({
template: `
<div class="posts">
<app-nav icon="prev" [link]="prev" [disabled]="!prev"></app-nav>
<div class="card mx-4">
<div class="card-body">
<router-outlet></router-outlet>
</div>
</div>
<app-nav icon="next" [link]="next" [disabled]="!next"></app-nav>
</div>
`,
})
export class PostViewerComponent implements OnDestroy {
prev: string;
next: string;
private subscription: Subscription;
constructor(route: ActivatedRoute) {
const count$ = route.data.pipe(map(data => data.postCount));
const id$ = route.params.pipe(map(params => Number(params.id)));
this.subscription = id$.pipe(withLatestFrom(count$)).subscribe(([id, count]) => {
this.prev = id > 1 ? `../${id - 1}` : undefined;
this.next = id < count ? `../${id + 1}` : undefined;
});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment