我可以通过使用 Angular 的resolve来做到这一点。Resolve 允许您在加载路由组件之前访问路由和查询参数。
在您的情况下,我将创建一个看起来像这样的解析器类:
@Injectable()
export class FlagRouteResolver implements Resolve<any> {
constructor(private flagService: FlagService) {}
resolve(route: ActivatedRouteSnapshot) {
this.flagService.isFlagged = route.queryParamMap.get('flag');
// Need to return an observable for all resolve() methods
return Observable.of(null);
}
}
你的 AppModule 应该是这样的:
@NgModule({
imports: [
RouterModule.forRoot([{
path: 'flagRoute',
component: FlagComponent,
resolve: { test: FlagRouteResolver }
}]),
],
providers: [
FlagService,
FlagRouteResolver
],
declarations: [
FlagComponent
]
})
所以现在,在您的路由组件中,您应该能够立即在构造函数中访问该值,如下所示:
constructor(private flagService: FlagService) {
this.isFlagged = this.flagService.isFlagged;
}
但是如果你仍然想注入它,你也可以这样做:
providers: [{
provide: FLAG,
useFactory: (flagService: FlagService) => {
return this.flagService.isFlagged;
},
deps: [FlagService]
}]