1
votes
import { of as observableOf, Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import { Injectable, Injector } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild } from '@angular/router';

@Injectable()
export class MasterGuard implements CanActivate, CanActivateChild {
  constructor(private readonly injector: Injector) {}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    if (next.data.guards.canActivate && next.data.guards.canActivate.length > 0) {
      return this.executeGuardsCanActivate(next.data.guards.canActivate, next, state);
    } else {
      return true;
    }
  }

  executeGuardsCanActivate(guards, next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    let start = observableOf(true);
    guards.forEach(guard => {
      start = start.pipe(
        mergeMap(x => {
          if (x) {
            return this.injector.get(guard).canActivate(next, state);
          } else {
            return observableOf(false);
          }
        })
      );
    });

    return start;
  }
}

Above is the code which throws error while compiling after angular update from 6 to 7. Any help ?

ERROR in src/app/shared/guards/master.guard.ts(35,7): error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable'. Type '{}' is not assignable to type 'boolean'. src/app/shared/guards/master.guard.ts(52,7): error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable'.

Routing code

const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [MasterGuard],
    data: {
      guards: {
        canActivate: [AuthGuard, UserInformationGuard]
      }
    }
  },
1

1 Answers

4
votes

The issue is inside function executeGuardsCanActivate, and this particular line is the problem:

return this.injector.get(guard).canActivate(next, state);

Try with below instead:

return observableOf(this.injector.get(guard).canActivate(next, state));

Here is a sample code in Angular 9, but I believe it should also work for Angular 7: https://stackblitz.com/edit/angular-ivy-mn4h3p?file=src%2Fapp%2Fapp.service.ts

EDIT

New stackblitz link which works:

https://stackblitz.com/edit/angular-ivy-mccbhk?file=src%2Fapp%2Fapp.service.ts