Last active
April 19, 2021 09:51
-
-
Save armanozak/c40d2e8e1b15c57da939159813cc926e to your computer and use it in GitHub Desktop.
[Angular Reactivity Streamlined] Mapping reactive collections to reactive values with ng-observe #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 { ChangeDetectionStrategy, Component, Inject } from "@angular/core"; | |
import { ActivatedRoute } from "@angular/router"; | |
import { OBSERVE, Observed, ObserveFn, OBSERVE_PROVIDER, toMappedValue } from "ng-observe"; | |
import { map } from "rxjs/operators"; | |
@Component({ | |
template: ` | |
<div class="posts"> | |
<app-nav icon="prev" [link]="prev.value" [disabled]="!prev.value"></app-nav> | |
<div class="card mx-4"> | |
<div class="card-body"> | |
<router-outlet></router-outlet> | |
</div> | |
</div> | |
<app-nav icon="next" [link]="next.value" [disabled]="!next.value"></app-nav> | |
</div> | |
`, | |
changeDetection: ChangeDetectionStrategy.OnPush, | |
viewProviders: [OBSERVE_PROVIDER], | |
}) | |
export class PostViewerComponent { | |
prev: Observed<string>; | |
next: Observed<string>; | |
constructor(route: ActivatedRoute, @Inject(OBSERVE) observe: ObserveFn) { | |
const count = route.data.pipe(map(data => data.postCount)); | |
const id = route.params.pipe(map(params => Number(params.id))); | |
const state = observe({ count, id }); | |
this.prev = toMappedValue(state, ({ id }) => (id > 1 ? `../${id - 1}` : undefined)); | |
this.next = toMappedValue(state, ({ count, id }) => (id < count ? `../${id + 1}` : undefined)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment