You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 15中如何在CanActivate函数中注入BreakpointService

在Angular 15函数式CanActivate守卫中注入BreakpointService

步骤1:调整BreakpointService的注入配置

首先确保BreakpointService能被Angular注入器识别,给@Injectable添加全局提供配置,无需手动在模块的providers中注册:

import { Injectable } from '@angular/core';
import { BreakpointObserver, BreakpointState, Breakpoints } from '@angular/cdk/layout';
import { Observable, map, shareReplay } from 'rxjs';

@Injectable({ providedIn: 'root' })
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;
            });
    }

    // 可选:添加异步状态流,解决初始值不准确的问题
    get isMobile$(): Observable<boolean> {
        return this.breakpointObserver.observe([Breakpoints.Handset]).pipe(
            map(result => result.matches),
            shareReplay(1) // 缓存最新状态,避免重复订阅
        );
    }
}

步骤2:编写函数式CanActivate守卫

使用Angular内置的inject()函数,直接在守卫函数中获取BreakpointService实例:

方式一:使用同步属性(适合能接受初始默认值的场景)

import { CanActivateFn } from '@angular/router';
import { inject } from '@angular/core';
import { BreakpointService } from './breakpoint.service';

export const mobileOnlyGuard: CanActivateFn = () => {
  const breakpointService = inject(BreakpointService);
  return breakpointService.isMobile;
};

方式二:使用异步流(推荐,确保获取最新断点状态)

import { CanActivateFn } from '@angular/router';
import { inject } from '@angular/core';
import { BreakpointService } from './breakpoint.service';

export const mobileOnlyGuard: CanActivateFn = () => {
  const breakpointService = inject(BreakpointService);
  return breakpointService.isMobile$;
};

步骤3:在路由中配置守卫

直接将守卫函数传入路由的canActivate数组即可,无需额外注册:

import { Routes } from '@angular/router';
import { MobileComponent } from './mobile.component';
import { mobileOnlyGuard } from './mobile-only.guard';

export const routes: Routes = [
  {
    path: 'mobile',
    component: MobileComponent,
    canActivate: [mobileOnlyGuard]
  }
];

内容的提问来源于stack exchange,提问作者wonderful world

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 08:25:18