Skip to content

Instantly share code, notes, and snippets.

@JustDoItSascha
Last active September 16, 2022 23:15
Show Gist options
  • Save JustDoItSascha/c5e05e7a03bfff896646a37015292a5b to your computer and use it in GitHub Desktop.
Save JustDoItSascha/c5e05e7a03bfff896646a37015292a5b to your computer and use it in GitHub Desktop.
Splash Screen for Angular 8+ PWA
@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));
}
}
@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();
});
}
}
@JustDoItSascha
Copy link
Author

JustDoItSascha commented May 30, 2020 via email

@albinlang
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment