Last active
April 14, 2021 14:31
-
-
Save armanozak/0f81b333c38eee94eb964195099d41ef to your computer and use it in GitHub Desktop.
[Angular Reactivity Streamlined] Using route data and params in an Angular component #blog #angular #rxjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } 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 { | |
prev: string; | |
next: string; | |
constructor(route: ActivatedRoute) { | |
const count$ = route.data.pipe(map(data => data.postCount)); | |
const id$ = route.params.pipe(map(params => Number(params.id))); | |
id$.pipe(withLatestFrom(count$)).subscribe(([id, count]) => { | |
this.prev = id > 1 ? `../${id - 1}` : undefined; | |
this.next = id < count ? `../${id + 1}` : undefined; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment