我想重写 Router 的功能
navigate(commands: any[], extras?: NavigationExtras): Promise<boolean>
,始终将 queryParamsHandling
设置为 true
中的 NavigationExtras
。
因此我实现了以下课程:
@Injectable({
providedIn: 'root'
})
export class MmosRouter extends Router {
constructor(
rootComponentType: Type<any>,
urlSerializer: UrlSerializer,
contexts: ChildrenOutletContexts,
location: Location_2,
injector: Injector,
compiler: Compiler,
@Inject(ROUTES) config: Route[][]
) {
super(rootComponentType, urlSerializer, contexts, location, injector, compiler, flatten(config));
}
navigate(commands: any[], extras?: NavigationExtras): Promise<boolean> {
extras = { ...extras, queryParamsHandling: 'preserve' };
return super.navigate(commands, extras);
}
}
因为我想通过组件构造函数注入类,所以我必须将该类添加到
providers
中的 app.module.ts
。
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
...
{
provide: Router,
useFactory: (rootComponentType: Type<any>, urlSerializer: UrlSerializer, contexts: ChildrenOutletContexts, location: Location_2, injector: Injector, config: Route[][]) => {
return new MmosRouter(rootComponentType, urlSerializer, contexts, location, injector, config);
},
deps: [ApplicationRef, UrlSerializer, ChildrenOutletContexts, Location_2, Injector, Compiler, ROUTES]
},
...
],
bootstrap: [...],
exports: [
...
],
})
export class AppModule {
constructor(service: ApmService) {}
}
据我所知,这应该是让它发挥作用的一切。
但是,每当我启动应用程序时,我都会收到以下内容
NullInjectionError
:
core.mjs:9171 ERROR NullInjectorError: R3InjectorError(AppModule)[MmosRouter -> Function -> Function -> Function]:
NullInjectorError: No provider for Function!
at NullInjector.get (core.mjs:8191:27)
at R3Injector.get (core.mjs:8618:33)
at R3Injector.get (core.mjs:8618:33)
at R3Injector.get (core.mjs:8618:33)
at injectInjectorOnly (core.mjs:4782:33)
at Module.ɵɵinject (core.mjs:4786:12)
at Object.MmosRouter_Factory [as factory] (mmosRouter.ts:17:24)
at R3Injector.hydrate (core.mjs:8719:35)
at R3Injector.get (core.mjs:8607:33)
at ChainedInjector.get (core.mjs:13811:36)
(错误中提到的第17行,是
MmosRouting
的类签名)
您似乎正在尝试在某处注入 MmosRouter,并且该令牌没有提供任何内容,并且 Angular 尝试从构造函数参数解析令牌。
尝试
{
provide: MmosRouter,
useFactory: (rootComponentType: Type<any>, urlSerializer: UrlSerializer, contexts: ChildrenOutletContexts, location: Location_2, injector: Injector, config: Route[][]) => {
return new MmosRouter(rootComponentType, urlSerializer, contexts, location, injector, config);
},
deps: [ApplicationRef, UrlSerializer, ChildrenOutletContexts, Location_2, Injector, Compiler, ROUTES]
},
{
provide: Router,
useExisting: MmosRouter
}
这样您的应用程序就会知道如何构造
MmosRouter
并提供相同的实例来代替 Router