Last active
September 16, 2022 23:15
-
-
Save JustDoItSascha/c5e05e7a03bfff896646a37015292a5b to your computer and use it in GitHub Desktop.
Splash Screen for Angular 8+ PWA
This file contains 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
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class PwaService { | |
constructor( | |
private appRef: ApplicationRef, | |
private swUpdate: SwUpdate, | |
) { | |
if (this.swUpdate.isEnabled) { | |
this.appRef.isStable.pipe( | |
first(isStable => isStable === true), | |
switchMap(() => this.swUpdate.available), | |
).subscribe(() => { | |
this.swUpdate.activateUpdate().then(() => document.location.reload()); | |
}); | |
} | |
} | |
checkForUpdate(): Observable<boolean> { | |
const waitFor = 1000; | |
if (this.swUpdate.isEnabled) { | |
const available$ = this.swUpdate.available.pipe( | |
mapTo(true), | |
timeout(waitFor), | |
catchError(() => of(false)), | |
); | |
return fromPromise(this.swUpdate.checkForUpdate()).pipe( | |
switchMap(() => available$), | |
); | |
} | |
return timer(waitFor).pipe(mapTo(false)); | |
} | |
} |
This file contains 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
@Component({ | |
selector: 'app-splash-screen', | |
template: ` | |
<div class="splash-screen" *ngIf="show" @fadeOut> | |
// Your custom splash screen design | |
</div> | |
`, | |
animations: [ | |
// the fade-in/fade-out animation. | |
trigger('fadeOut', [ | |
transition(':leave', [ | |
query(':leave', animateChild(), {optional: true}), | |
animate(300, style({opacity: 0})) | |
]), | |
]), | |
], | |
styles: [` | |
.splash-screen { | |
position: absolute; | |
top: 0; | |
right: 0; | |
bottom: 0; | |
left: 0; | |
z-index: 9999; | |
} | |
`], | |
changeDetection: ChangeDetectionStrategy.OnPush | |
}) | |
export class SplashScreenComponent implements OnInit { | |
show = true; | |
constructor( | |
private pwaService: PwaService, | |
private cdr: ChangeDetectorRef, | |
private appRef: ApplicationRef, | |
) { | |
} | |
ngOnInit() { | |
this.pwaService.checkForUpdate() | |
.subscribe(result => { | |
this.show = result; | |
this.cdr.detectChanges(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have no idea what was going wrong in the first place but I created a new project and managed to get it to work.
Public repo here.