@ashetm/ng-network

中文文档
1.0.1发布于 2026/10/31TypeScriptES Module

@ashetm/ng-network is a library that provides a directive, RxJS observables and an RxJS operator to follow the network state of the device (online/offline, connection quality).

原始使用文档
文档目录9 节
  1. Compatibility Table
  2. Install
  3. API
  4. Directives
  5. Custom RXJS Observables
  6. Custom RXJS Operators
  7. Types
  8. Server-side rendering
  9. Issue

@ashetm/ng-network

@ashetm/ng-network is a library that provides a directive, RxJS observables and an RxJS operator to follow the network state of the device (online/offline, connection quality).

Compatibility Table

Angular Version@ashetm/ng-network VersionRxJS VersionSupport
Angular 16.x – 19.x@ashetm/ng-network 1.x6.6.x and +✅

Install

You can install it with npm:

npm install @ashetm/ng-network

API

@ashetm/ng-network exposes the following:

Directives

NetworkDirective

  • Selector: [ashetmNetwork]

This Angular standalone structural directive listens for changes in the network connection status and provides observable data about the network's current state and the time elapsed since the connection was lost. It uses fromNetworkEvents to detect online/offline status and fromNetworkLastTimeConnected to track the time elapsed since the device was last connected.

Usage Example:

Import the standalone NetworkDirective in your component (or NgModule) imports:

@Component({
  standalone: true,
  imports: [AsyncPipe, NgIf, NetworkDirective],
  // ...
})
<ng-template ashetmNetwork let-network let-lastTimeConnected$="lastTimeConnected$">
  <div *ngIf="network | async">You are online</div>
  <div *ngIf="!(network | async)">You are offline</div>
  <div *ngIf="lastTimeConnected$ | async as lastConnected">Last connected: {{ lastConnected }} ms ago</div>
</ng-template>

Or with the structural shorthand:

<div *ashetmNetwork="let network; lastTimeConnected$ as lastTimeConnected$">
  {{ (network | async) ? 'You are online' : 'You are offline' }}
</div>

Explanation:

  • network: This observable emits the current state first, then true when the device goes online and false when it goes offline.
  • lastTimeConnected$: This observable emits, every 100 ms while the device is offline, the time elapsed in milliseconds since the connection was lost. It emits undefined while the device is online.

Custom RXJS Observables

fromOfflineEvent()

function fromOfflineEvent(): Observable<void> { ... }

Emits a notification when the device goes offline.

Returns:

An observable emitting a void.

Example:

fromOfflineEvent().subscribe(() => {
  console.log('Device is offline');
});

fromOnlineEvent()

function fromOnlineEvent(): Observable<void> { ... }

Emits a notification when the device goes online.

Example:

fromOnlineEvent().subscribe(() => {
  console.log('Device is online');
});

fromNetworkEvents()

function fromNetworkEvents(): Observable<boolean> { ... }

Emits the current state on subscribe (navigator.onLine), then true when the device goes online and false when it goes offline. Repeated values are skipped.

Example:

fromNetworkEvents().subscribe((isOnline: boolean) => {
  console.log(`Network status: ${isOnline ? 'Online' : 'Offline'}`);
});

fromNetworkLastTimeConnected()

function fromNetworkLastTimeConnected(): Observable<number | undefined> { ... }

While the device is offline, emits every 100 ms the time elapsed (in milliseconds) since the connection was lost. Emits undefined while the device is online.

Example:

fromNetworkLastTimeConnected().subscribe((lastConnected: number | undefined) => {
  if(typeof lastConnected === 'number')
    console.log(`Last connected: ${lastConnected} ms ago`);
  else
    console.log(`Last connected: is currently connected`);
});

fromNetworkStatus()

function fromNetworkStatus(): Observable<NetworkStatus | undefined> { ... }

This observable provides detailed network status information (see NetworkStatus), based on the Network Information API. It emits the current status on subscribe, then whenever the network conditions change.

It emits undefined when the browser doesn't support the Network Information API.

Example:

fromNetworkStatus().subscribe((status: NetworkStatus | undefined) => {
  if (!status) {
    console.log('Network Information API not supported');
    return;
  }

  console.log(`Effective type: ${status.effectiveType}`);
  console.log(`Downlink: ${status.downlink} Mbps`);
  console.log(`RTT: ${status.rtt} ms`);
  console.log(`Data Saver Enabled: ${status.saveData}`);
});

Custom RXJS Operators

retryUntilOnline()

function retryUntilOnline<T>(durationStep: number = 1000, timeIncreasing: boolean = false): MonoTypeOperatorFunction<T>  { ... }

The retryUntilOnline operator is an experimental feature that retries an observable operation when it fails because the device is offline:

  • If the source fails while the device is offline, it waits until the device is back online, then retries after durationStep.
  • If the source fails while the device is online, the error is passed through (it isn't a network problem).

Parameters:

  • durationStep: The delay in milliseconds before retrying, once the device is back online (default is 1000 ms).
  • timeIncreasing: When true, the delay is multiplied by the attempt number (1×, 2×, 3×…) (default is false).

Example:

import { of } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { catchError, tap } from 'rxjs/operators';

import { retryUntilOnline } from '@ashetm/ng-network';

// Mock API endpoint
const apiEndpoint = 'https://jsonplaceholder.typicode.com/posts/1';

// Simulated HTTP request
const httpRequest$ = ajax.getJSON(apiEndpoint).pipe(
  tap((response) => console.log('Request successful:', response)),
  retryUntilOnline(1000), // If offline, wait for the network, then retry 1 second later
  catchError((error) => {
    console.error('Request failed:', error);
    return of(null); // Handle the error and emit a fallback value
  })
);

// Subscribe to the observable
httpRequest$.subscribe({
  next: (data) => console.log('Final data:', data),
  error: (err) => console.error('Subscription error:', err),
  complete: () => console.log('Request completed'),
});

Types

NetworkStatus

The NetworkStatus interface defines the structure of the network status object emitted by the fromNetworkStatus() observable.

Parameters:

  • effectiveType: A string representing the effective network connection type (e.g., 4g, 3g, 2g, or slow-2g).
  • downlink: The approximate bandwidth of the connection in megabits per second.
  • rtt: The estimated round-trip time for requests in milliseconds.
  • saveData: A boolean indicating whether the user has enabled the browser's data-saver mode.

Server-side rendering

The library is safe to use with server-side rendering. On the server, where there is no browser:

  • fromOnlineEvent() and fromOfflineEvent() emit nothing.
  • fromNetworkEvents() emits true (assumes online).
  • fromNetworkLastTimeConnected() and fromNetworkStatus() emit undefined.
  • retryUntilOnline passes errors through.

Issue

LOOKING FOR MAINTAINER OR IF THERE IS AN ISSUE OR ANY IDEA TO ADD. PLEASE CREATE ISSUE IN GITHUB REPOSITORY.

版本与发布记录

@ashetm/ng-network 共发布 2 个版本,首次发布于 2025/01/14;过去 12 个月发布了 1 个版本。

版本发布日期距今
1.0.1latest2026/10/312 天前
1.0.02025/01/141.8 年前

关于 @ashetm/ng-network 的常见问题

@ashetm/ng-network 是什么?

@ashetm/ng-network 是一个库,它提供了一个指令、RxJS observable和一个RxJS操作符来跟踪设备的网络状态(在线/离线、连接质量)。

如何安装 @ashetm/ng-network?

在项目目录运行 npm install @ashetm/ng-network,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:rxjs(>=6.6.0)、@angular/core(>=16.0.0 <20.0.0)、@angular/common(>=16.0.0 <20.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ashetm/ng-network 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ashetm/ng-network 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@ashetm/ng-network 可以商用吗?

@ashetm/ng-network 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@ashetm/ng-network 还在维护吗?

最新版本 1.0.1 发布于 2026/10/31(2 天前);至今共发布 2 个版本,其中过去 12 个月发布了 1 个;首次发布于 2025/01/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。