import { Injectable } from '@angular/core' ; import { CanDeactivate , ActivatedRouteSnapshot , RouterStateSnapshot } from '@angular/router' ; import { MatDialog } from '@angular/material' ; import { of , forkJoin } from 'rxjs' ; import { switchMap , catchError , take } from 'rxjs/operators' ; import { UserService } from '../user/user.service' ; import { LabStorageService } from '../lab-storage.service' ; import { EditorViewComponent } from './editor-view/editor-view.component' ; import { NavigationConfirmDialogComponent , NavigationConfirmReason } from './navigation-confirm-dialog/navigation-confirm-dialog.component' ; import { LabExecutionService } from '../lab-execution.service' ; @ Injectable ( ) export class HasRunningExecutionGuard implements CanDeactivate < EditorViewComponent > { constructor ( private labExecutionService , private dialog , private userService , private labStorageService ) { } canDeactivate ( component , currentRoute , currentState , nextState ) { const labId = currentRoute . paramMap . get ( 'id' ) ; if ( nextState . url . indexOf ( labId ) > - 1 ) { return of ( true ) ; } return forkJoin ( this . labStorageService . getLab ( labId ) , this . userService . getCurrentUser ( ) ) . pipe ( switchMap ( val => this . userService . isLoggedInUser ( val [ 0 ] . user_id ) ) , switchMap ( userOwnsLab => { if ( ! userOwnsLab ) { return of ( true ) ; } return this . labExecutionService . labHasRunningExecutions ( labId ) . pipe ( switchMap ( val => ( val ? this . showDialog ( ) : of ( true ) ) ) ) ; } ) , catchError ( _ => { return of ( true ) ; } ) ) ; } private showDialog ( ) { return this . dialog . open ( NavigationConfirmDialogComponent , { data : { reason : NavigationConfirmReason . RunningExecutions } } ) . afterClosed ( ) ; } }