【问题标题】:Could not Detect Online Connectivity in Angular 11无法在 Angular 11 中检测到在线连接
【发布时间】:2021-07-28 15:46:35
【问题描述】:

我尝试在 Angular 11 中显示在线状态。 我做了同样的事情https://dzone.com/articles/how-to-detect-the-internet-connection-status-in-an

我的 ts.file

import { ConnectionService } from 'ng-connection-service';

  isConnected = true;  
  noInternetConnection: boolean; 

 constructor(private connectionService: ConnectionService,) {

    this.connectionService.monitor().subscribe(isConnected => {  
      this.isConnected = isConnected;  
      if (this.isConnected) {  
        this.noInternetConnection=false; 
      }  
      else {  
        this.noInternetConnection=true;
      }  
      
    })  
  }

my.html 文件

  <nb-action *ngIf="noInternetConnection">
      <p>online</p>
    </nb-action>
    <nb-action *ngIf="!noInternetConnection">
      <p>offline</p>
    </nb-action>

但它显示离线。我的 wifi 连接已开启

谁能帮我找出错误?

【问题讨论】:

  • 我在我的 html 代码中发现了我的错误。应该是&lt;nb-action *ngIf="noInternetConnection"&gt; &lt;p&gt;offline&lt;/p&gt; &lt;/nb-action&gt; &lt;nb-action *ngIf="!noInternetConnection"&gt; &lt;p&gt;online&lt;/p&gt; &lt;/nb-action&gt;

标签: angular11


【解决方案1】:

我个人不建议使用其他库来监听本机浏览器事件,因为这会使应用程序更加健壮,并且可能该库与以下代码相同:(

当我实现这样的功能时,我为本地“在线”和“离线”事件创建了事件侦听器。

这里是网络监控服务。

import { Injectable } from '@angular/core';
import { fromEvent, ReplaySubject } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';

@Injectable()
export class NetworkStatusService {

  private init: boolean = navigator.onLine;
  private online: ReplaySubject<boolean> = new ReplaySubject();

  get initStatus() {
    return this.init
  }
  constructor() {
    if (this.init==false) {
      this.online.next(false);
    }
    fromEvent(window, "online").subscribe((val) => {
      this.online.next(true);
    })

    fromEvent(window, "offline").subscribe((val) => {
      this.online.next(false);
    })
  }

  getOnlineStatus() {
    return this.online.pipe(distinctUntilChanged());
  }
}

【讨论】:

  • 感谢您的宝贵时间。但是我发现了我的错误。所以我不尝试你的代码。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-25
  • 2020-05-05
  • 2021-05-26
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
相关资源
最近更新 更多