import { Injectable } from '@angular/core' ; import { CanActivate , ActivatedRouteSnapshot , RouterStateSnapshot , Router , ActivatedRoute } from '@angular/router' ; import { MatSnackBar } from '@angular/material' ; import { of } from 'rxjs' ; import { map , tap , switchMap , catchError } from 'rxjs/operators' ; import { LabExecutionService } from '../lab-execution.service' ; import { LocationHelper } from '../util/location-helper' ; @ Injectable ( ) export class HasValidExecutionGuard implements CanActivate { constructor ( private router , private labExecutionService , private locationHelper , private snackBar , private route ) { } canActivate ( route ) { const labId = route . paramMap . get ( 'id' ) ; const executionId = route . paramMap . get ( 'executionId' ) ; const checkForLatestExecution$ = this . labExecutionService . getLatestVisibleExecutionIdForLab ( labId ) . pipe ( tap ( _executionId => { const rootUrlSegment = this . locationHelper . getRootUrlSegment ( ) ; const urlSegments = [ `/${ rootUrlSegment }` , labId ] ; if ( _executionId ) { urlSegments . push ( _executionId ) ; } this . router . navigate ( urlSegments , { queryParamsHandling : 'merge' } ) ; } ) , map ( _executionId => ! _executionId ) ) ; return ! executionId ? checkForLatestExecution$ : this . labExecutionService . executionExistsAndVisible ( executionId ) . pipe ( switchMap ( exists => ( exists ? of ( true ) : checkForLatestExecution$ ) ) , catchError ( _ => { this . snackBar . open ( "This lab doesn't exist anymore" , 'Dismiss' , { duration : 3000 } ) ; this . router . navigate ( [ '/editor' ] ) ; return of ( false ) ; } ) ) ; } }