如何在Angular2中检查用户是否有互联网连接? [英] How to check whether user has internet connection or not in Angular2?

查看:445
本文介绍了如何在Angular2中检查用户是否有互联网连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在API点击时检查Angular2中的互联网连接,每当我的应用程序API被点击到服务器时,有时用户是
离线(我的意思是没有互联网连接)所以我如何检查互联网连接?是否有一些特殊的互联网连接状态代码?
或其他什么?

How I would check internet connection in Angular2 at the time of API hitting, whenever in my app API is hit to server sometimes user is offline (i mean without internet connection) so how would i check the internet connectivity ? is there some special status code for internet connectivity ? or something else ?

PS: - 我在angularJs中找到了 navigator.onLine 但似乎没有在angular2中工作。

PS:- i found navigator.onLine in angularJs but seems not working in angular2.

  • Source - How to check internet connection in AngularJs

正如sudheer在下面的回答中建议的那样 navigator.onLine 使用angular2但仍然无法正常工作原因?
此处的工作示例

as sudheer suggested in answer below navigator.onLine in working with angular2 but still not working properly why ? working example here

推荐答案

(2018)为rxjs6更新的代码

(2018) Code updated for rxjs6

它完全适用于angular2。显然它与angularJS不同,因为$ scope和$ apply都不再存在。不过,RxJS让这很简单!在Chrome 53上测试:

It totally works with angular2. Obviously it's different from angularJS because neither $scope nor $apply exist anymore. RxJS makes this easy, though! Tested on Chrome 53:

模板:

<p>{{online$ | async}}</p>

组件:

import { fromEvent, merge, of } from 'rxjs';
import { mapTo } from 'rxjs/operators';

@Component({ /* ... */ })
export class MyComponent {
  online$: Observable<boolean>;

  constructor() {
    this.online$ = merge(
      of(navigator.onLine),
      fromEvent(window, 'online').pipe(mapTo(true)),
      fromEvent(window, 'offline').pipe(mapTo(false))
    );
  }
}

这篇关于如何在Angular2中检查用户是否有互联网连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆