在 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)
请问如何解决这个问题?
不能直接注入 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));
}
}