Forked from NetanelBasal/connection.component.ts
Last active
October 19, 2018 06:44
-
-
Save LayZeeDK/10dbedc0893b033816711b0d5521f769 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, ContentChild } from '@angular/core'; | |
import { map } from 'rxjs/operators'; | |
import { ConnectionService } from './connection.service'; | |
import { FastDirective} from './fast.directive'; | |
import { SlowDirective} from './slow.directive'; | |
@Component({ | |
selector: 'connection', | |
template: ` | |
<ng-template [ngTemplateOutlet]="fast.tpl" *ngIf="isFast| async"></ng-template> | |
<ng-template [ngTemplateOutlet]="slow.tpl" *ngIf="!isFast | async"></ng-template> | |
`, | |
}) | |
export class ConnectionComponent { | |
isFast$ = this.connection.effectiveTypeWithFallback('4g').pipe( | |
map(effectiveType => !/slow-2g|2g|3g/.test(effectiveType)), | |
); | |
@ContentChild(FastDirective) fast: FastDirective; | |
@ContentChild(SlowDirective) slow: SlowDirective; | |
constructor(private readonly connection: ConnectionService) {} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { empty, Observable, of } from 'rxjs'; | |
import { shareReplay } from 'rxjs/operators'; | |
@Injectable({ | |
providedIn: 'root', | |
}) | |
export class ConnectionService { | |
private static readonly browserSupport = | |
navigator.connection && navigator.connection.effectiveType; | |
private readonly effectiveType$ = | |
(!ConnectionService.browserSupport) | |
? empty() | |
: new Observable(observer => { | |
const { effectiveType } = navigator.connection; | |
observer.next(effectiveType); | |
const onConnectionChange = () => { | |
const { effectiveType } = navigator.connection; | |
observer.next(effectiveType); | |
} | |
navigator.connection.addEventListener('change', onConnectionChange) | |
return () => { | |
navigator.connection.removeEventListener('change', onConnectionChange); | |
}; | |
}.pipe( | |
shareReplay(1), | |
); | |
effectiveTypeWithFallback(fallback = 'slow-2g') { | |
return (!ConnectionService.browserSupport) | |
? of(fallback) | |
: this.effectiveType$; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment