我试图根据路线名创建新的类实例。似乎订阅的解决方案是使用Factory Provider。但问题是,在调用路由之前,首先初始化提供程序。这就是我所拥有的
应用-routing.module.ts
import {InitializerComponent} from "./components/initializer.component";
@NgModule({
imports: [
RouterModule.forRoot([
{ path : 'category/:id', component: InitializerComponent},
{ path : 'product/:id', component: InitializerComponent}
])
],
exports: [
RouterModule
]
})
export class AppRoutingModule {}
我-factory.service.ts
import {ProductService} from 'product.service';
import {CategoryService} from 'category.service'
let myFactoryService = (route_name) => {
var my_services = {
product : ProductService,
category : CategoryService
}
return new my_services[route_name](dependencies here...);
};
export let MyServiceProvider =
{ provide: myDynamicService,
useFactory: myFactoryService,
deps: [some deps here...]
};
现在在我的组件中使用它
initializer.component.ts
import { Component} from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { MyServiceProvider } from 'my-factory.service';
@Component({
selector: 'initializer-component',
template: `
<div>Create Instace of class based on route name</div>
`,
providers: [MyServiceProvider]
})
export class InitializerComponent {
constructor(private route: ActivatedRoute,
private router: Router) {}
ngOnInit() {
var self = this;
this.route.params.forEach((params: Params) => {
// get route name here
var route_name = this.route_name; // just sample code
// create new instance of class here based on route name
var my_service = new MyServiceProvider(route_name);
// but providers is declared in the component how can we call the factory service here?
});
}
}
这在工厂提供商中是否可行?
修改 这里的问题是如何将路由名称传递给MyServiceProvider以创建动态服务实例?
谢谢,感谢您的帮助。