Skip to content

Instantly share code, notes, and snippets.

@armanozak
Created April 15, 2021 07:50
Show Gist options
  • Save armanozak/c081c6474416754185d296d4da4139e1 to your computer and use it in GitHub Desktop.
Save armanozak/c081c6474416754185d296d4da4139e1 to your computer and use it in GitHub Desktop.
[Angular Reactivity Streamlined] Using ng-observe to observe and react to emitted values #blog #angular #rxjs
import { ChangeDetectionStrategy, Component, Inject } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { OBSERVE, Observed, ObserveFn, OBSERVE_PROVIDER } 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 count: Observed<number>;
private id: Observed<number>;
get prev(): string {
return this.id.value > 1 ? `../${this.id.value - 1}` : undefined;
}
get next(): string {
return this.id.value < this.count.value ? `../${this.id.value + 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.count = observe(count$);
this.id = observe(id$);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment