首页 新闻 会员 周边 捐助

angular 中注入 ActivatedRouteSnapshot 报错 "NG0204: Can't resolve all parameters for ActivatedRouteSnapshot"

0
悬赏园豆:30 [已解决问题] 解决于 2025-01-11 14:04

在 angular 19 项目的一个 Directive 实现中通过构造函数注入 ActivatedRouteSnapshot

@Directive({
    selector: '[cnbLayoutSidebar]',
    providers: [ActivatedRouteSnapshot]
})
export class LayoutSidebarDirective implements OnInit, AfterViewChecked {
    constructor(private readonly activatedRouteSnapshot: ActivatedRouteSnapshot) { }

    ngOnInit() {}

    ngAfterViewChecked(): void {
        console.log(JSON.stringify(this.activatedRouteSnapshot));
    }
}

运行时报错

Uncaught RuntimeError: NG0204: Can't resolve all parameters for ActivatedRouteSnapshot: (?, ?, ?, ?, ?, ?, ?, ?, ?).
    at getUndecoratedInjectableFactory (core.mjs:2337:11)
    at injectableDefOrInjectorDefFactory (core.mjs:2328:12)
    at providerToFactory (core.mjs:2371:48)
    at resolveProvider (core.mjs:31216:29)
    at resolveProvider (core.mjs:31209:7)
    at providersResolver (core.mjs:31196:5)
    at definition.providersResolver (core.mjs:31437:14)
    at initializeDirectives (core.mjs:13358:36)
    at resolveDirectives (core.mjs:13334:7)
    at templateFirstCreatePass (core.mjs:20034:3)

请问如何解决这个问题?

dudu的主页 dudu | 高人七级 | 园豆:28665
提问于:2025-01-11 12:56
< >
分享
最佳答案
0

不能直接注入 ActivatedRouteSnapshot,需要通过 ActivatedRoute

@Directive({
    selector: '[cnbLayoutSidebar]'
})
export class LayoutSidebarDirective implements OnInit, AfterViewChecked {
    private activatedRouteSnapshot: ActivatedRouteSnapshot;

    constructor(activatedRoute: ActivatedRoute) { 
        this.activatedRouteSnapshot = activatedRoute.snapshot;
    }

    ngOnInit() { }

    ngAfterViewChecked(): void {
        console.log(JSON.stringify(this.activatedRouteSnapshot));
    }
}

答案来自 Unable to inject ActivatedRouteSnapshot 的回答

dudu | 高人七级 |园豆:28665 | 2025-01-11 14:04
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册