Forked from tanishqmanuja/network-indicator.component.ts
Created
September 8, 2024 08:26
-
-
Save billyjov/e4d5b2822b1a4caafc5e7c157431deab to your computer and use it in GitHub Desktop.
Network Indicator using @ngxtension
This file contains 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 { AsyncPipe } from "@angular/common"; | |
import { Component } from "@angular/core"; | |
import { takeUntilDestroyed, toObservable } from "@angular/core/rxjs-interop"; | |
import { injectNetwork } from "ngxtension/inject-network"; | |
import { | |
distinctUntilChanged, | |
map, | |
skipWhile, | |
startWith, | |
switchMap, | |
timer, | |
} from "rxjs"; | |
const INDICATOR_TIMEOUT_MS = 2 * 1000; | |
const INDICATOR_TRANSITION_MS = 300; | |
@Component({ | |
standalone: true, | |
selector: "app-network-indicator", | |
imports: [AsyncPipe], | |
template: ` | |
@let isOnline = isOnline$ | async; | |
<div | |
class="indicator" | |
[class.visible]="isVisible$ | async" | |
[style.background]="isOnline ? 'green' : 'red'" | |
> | |
{{ isOnline ? "Online" : "Offline" }} | |
</div> | |
`, | |
styles: ` | |
.indicator { | |
text-align: center; | |
display: none; | |
opacity: 0; | |
transition: opacity ${INDICATOR_TRANSITION_MS}ms ease, | |
display ${INDICATOR_TRANSITION_MS}ms ease allow-discrete; | |
&.visible { | |
opacity: 1; | |
display: block; | |
} | |
} | |
@starting-style { | |
.indicator.visible { | |
opacity: 0; | |
} | |
} | |
`, | |
}) | |
export class NetworkIndicatorComponent { | |
private readonly network = injectNetwork(); | |
protected readonly isOnline$ = toObservable(this.network.online).pipe( | |
skipWhile(Boolean), | |
distinctUntilChanged(), | |
takeUntilDestroyed() | |
); | |
protected readonly isVisible$ = this.isOnline$.pipe( | |
switchMap(() => | |
timer(INDICATOR_TIMEOUT_MS).pipe( | |
map(() => false), | |
startWith(true) | |
) | |
) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment