Forked from tanishqmanuja/network-indicator.component.ts
Created
September 8, 2024 05:50
-
-
Save sharbel93/0b631a4b3f386fde5e8c9d2a95f415d2 to your computer and use it in GitHub Desktop.
Network Indicator using @ngxtension
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 { 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