我想在实例化路由/组件之前获取数据。因此,我想使用Angular2-Routing-Module中的“Resolver”接口。
看看我的代码。它使用字符串作为提供者名称,但如果我为提供者使用OpaqueToken,则会抛出错误。
注意“不工作” - 。
export const routes: Routes = [{
path: 'myPath',
component: MyComponent,
children: [
{
path: ':id',
component: MyComponent,
resolve: {
itemData: 'MyResolver' // WORKING --- wanted to replace with itemData: MyToken
}
}
]
}];
export let MyToken: OpaqueToken = new OpaqueToken('my.resolver');
@NgModule({
imports: [
CommonModule,
...
],
declarations: [
MyComponent,
],
providers: [
{
provide: 'MyResolver', // WORKING -- wanted to replace with provide: MyToken
useFactory: (DataService: any) => {
return new MyResolverService(DataService);
},
deps: [MyInstanceOfDataService]
}
]
})
export class MyModule {
}
@Injectable()
export class MyResolverService implements Resolve<any> {
constructor(protected DataService: any) {
}
resolve(ActivatedRoute: ActivatedRouteSnapshot): Promise<any> {
return this.DataService.getItem(id).toPromise()
.then((response: any}) => {
return response;
});
}
}
无法用创建的OpaqueToken(“MyToken” - 当然没有引号)替换字符串(“myResolver”)。不知道为什么。我为多个提供商使用多个OpaqueToken,但解析器无法使用它。
控制台中的错误消息如下所示,没有进一步的信息。
错误:必须定义令牌!
有人有任何想法吗?
答案 0 :(得分:0)
// import MyResolver and MyToken here
export const routes: Routes = [{
path: 'myPath',
component: MyComponent,
children: [
{
path: ':id',
component: MyComponent,
resolve: {
itemData: MyResolver
itemData: MyToken
}
}
]
}];