简体   繁体   English

在APP_INITIALIZER启动服务之前访问路由参数值-angular2

[英]Accessing route param value before APP_INITIALIZER startup service - angular2

If I'm using startup service to check certain business rules (retrieved over web service) and upon that information I grant or denied access to the app 如果我使用启动服务来检查某些业务规则(通过Web服务检索),并根据该信息授予或拒绝访问该应用程序

inside app.module startup service is registered as follows ... 内部app.module启动服务注册如下...

const APP_PROVIDERS = [
  AppState,
  GlobalState
];

export function startupServiceFactory(startupService: StartupService): Function {
  return () => startupService.load();
}
@NgModule({
    bootstrap: [App],
    declarations: [
        App    
    ],
    imports: [ 
        ...
    ]
    providers: [
        DataService,    
        StartupService,
        APP_PROVIDERS,
        {
            // Provider for APP_INITIALIZER
            provide: APP_INITIALIZER,
            useFactory: startupServiceFactory,
            deps: [StartupService],
            multi: true
        }
    ],
})

export class AppModule {
  constructor(public appState: AppState) { }
}

Now I want further to extend this. 现在我想进一步扩展。 I want to fetch route param value before startup service is entered, and to pass this param value to the startup service. 我想在进入启动服务之前获取路由参数值,并将该参数值传递给启动服务。

So I tried following, 所以我尝试跟随

app.routing.ts
export const routes: Routes = [    
  { path: 'myapp/:name', component: AppComponent }   
];

inside AppComponent I tried to fetch this on init AppComponent内部,我尝试在init上获取

ngOnInit() {    
    let name = this.route.snapshot.params["name"];
    storageService.save('nameValue', name);
 }

startupService.ts startupService.ts

 export class StartupService{
    private name: string;
    constructor(private storage: StorageService){
        this.name = storage.get(nameValue); 
    } 

    // using this.name further ... 
 }

This not working since startupService is loaded before AppComponent and therefore name variable inside StartupService is always undefined. 由于启动服务是在AppComponent之前加载的,因此这不起作用,因此StartupService内部的名称变量始终是未定义的。

How can I change this to inject route param value to the startup service over storage service (or any other way)? 如何更改此参数以通过存储服务(或任何其他方式)将路由参数值注入到启动服务?

在startupServiceFactory中,我将直接使用window.location,解析queryparam,然后保存值(全部在startupServiceFactory中),然后在下游可以使用更多的“纯”角度代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM