(2018) Code updated for rxjs6
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:
template:
<p>{{online$ | async}}</p>
component:
import { Observable, 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))
);
}
}
Think about what ‘offline’ means for your use case!
An unplugged ethernet cable and a 3KB/s EDGE connection likely have the same implications for your app although the latter means you’re not technically offline!
From a programmer’s point-of-view being connected wirelessly with a very poor signal is actually a lot worse than being truely disconnected because it’s a lot harder to detect!
The above code returning a false value means your absolutely offline as in disconnected. It returning true doesn’t necessarily indicate that there’s a practically usable connection.