Last active
April 15, 2021 13:39
-
-
Save armanozak/a78d9412d3fa5c24bb6d3106ec7728bb to your computer and use it in GitHub Desktop.
[Angular Reactivity Streamlined] Using ng-observe to observe a collection of emitted values #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, ObserveFn, OBSERVE_PROVIDER, toValue } from "ng-observe"; | |
import { map } 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> | |
`, | |
changeDetection: ChangeDetectionStrategy.OnPush, | |
viewProviders: [OBSERVE_PROVIDER], | |
}) | |
export class PostViewerComponent { | |
private state = { | |
count: 0, | |
id: 0, | |
}; | |
get prev(): string { | |
const { id } = this.state; | |
return id > 1 ? `../${id - 1}` : undefined; | |
} | |
get next(): string { | |
const { count, id } = this.state; | |
return id < count ? `../${id + 1}` : undefined; | |
} | |
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))); | |
this.state = observe({ count, id }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment