Skip to content

Instantly share code, notes, and snippets.

@armanozak
Last active April 15, 2021 13:39
Show Gist options
  • Save armanozak/a78d9412d3fa5c24bb6d3106ec7728bb to your computer and use it in GitHub Desktop.
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
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