angularangular-routingangular-route-guards

Using CanActivate and BreakpointObserver in Angular 15


The Angular 15 suggests using any JavaScript function as a CanActivate guard. I want to use BreakpointObserver inside this method. I have a BreakpointService which takes BreakpointObserver as a dependency.

export const isMobile = () => {
    return true;
}
import { Injectable } from '@angular/core';
import { BreakpointObserver, BreakpointState, Breakpoints } from '@angular/cdk/layout';

@Injectable()
export class BreakpointService {

    isDesktop = false;
    isMobile = false;

    constructor(public breakpointObserver: BreakpointObserver) {
        this.breakpointObserver
            .observe([Breakpoints.Handset])
            .subscribe((result: BreakpointState) => {
                this.isMobile = result.matches;
                this.isDesktop = !this.isMobile;
            });
    }
}

What should I do to inject BreadkpointService into the CanActivate function to use it's properties isMobile or isDesktop?


Solution

  • You can use inject function to resolve dependency

    import { inject } from '@angular/core';    
    export function customCanActive(...arg): CanMatchFn {
                const breakpointService = inject(BreakpointService);
                ....
     }