我想覆盖Router ::导航并直接在Router类(例如log)中执行一些代码
export const routes: Routes = [
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}
];
export function routerFactory(rootComponentType: Type<any> | null, urlSerializer: UrlSerializer,
rootContexts: ChildrenOutletContexts, location: Location,
injector: Injector, loader: NgModuleFactoryLoader,
compiler: Compiler, config: Router): Router {
return new MyRouter(
rootComponentType,
urlSerializer,
rootContexts,
location,
injector,
loader,
compiler,
config
);
}
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
routing,
...
],
providers: [
...
{
provide: Router,
useFactory: routerFactory,
deps: [Type, UrlSerializer, ChildrenOutletContexts, Location, Injector,
NgModuleFactoryLoader, Compiler, router]
}
],
bootstrap: [AppComponent]
})
使用该代码,我有错误:
Error: Can't resolve all parameters for routerFactory: (
[object Object],
[object Object],
[object Object],
[object Object],
[object Object],
[object Object],
[object Object],
?)
我错过了什么吗?我可以用工厂覆盖路由器组件吗?
为什么棱角不能注入我的路线?
答案 0 :(得分:0)
我使用以下代码(Angular v6.0.3)覆盖了默认的angular Router.navigate功能:
export class MyRouter extends Router {
constructor(rootComponentType: Type<any>, urlSerializer: UrlSerializer,
rootContexts: ChildrenOutletContexts, location: Location, injector: Injector,
loader: NgModuleFactoryLoader, compiler: Compiler, config: Routes) {
super(rootComponentType, urlSerializer, rootContexts, location, injector, loader, compiler, config);
}
navigate(commands: any[], extras: NavigationExtras = { skipLocationChange: false }): Promise<boolean> {
...
return super.navigate(commands, extras);
}
}
function flatten<T>(arr: T[][]): T[] {
return Array.prototype.concat.apply([], arr);
}
export function routerFactory(rootComponentType: Type<any>, urlSerializer: UrlSerializer,
rootContexts: ChildrenOutletContexts, location: Location, injector: Injector,
loader: NgModuleFactoryLoader, compiler: Compiler, config: Route[][]): Router {
return new MyRouter(
rootComponentType,
urlSerializer,
rootContexts,
location,
injector,
loader,
compiler,
flatten(config)
);
}
@NgModule({
declarations: [
AppComponent
],
imports: [
RouterModule.forRoot([]),
...
],
providers: [
{
provide: Router,
useFactory: routerFactory,
deps: [ApplicationRef, UrlSerializer, ChildrenOutletContexts, Location, Injector,
NgModuleFactoryLoader, Compiler, ROUTES]
},
...
],
bootstrap: [AppComponent]
})
export class AppModule { }