问题描述
如何在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 isoffline (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 ?
推荐答案
(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中检查用户是否有互联网连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!