0

我有一个ConfigService写在角应用引导前获取配置的详细信息。如何在angular4中读取APP_INITIALIZER服务中的查询参数?

下面的代码是写在app.module.ts这段代码工作正常,我可以在加载应用程序之前加载配置。

... 
providers: [ 
    { 
     provide: APP_INITIALIZER, 
     useFactory: configServiceFactory, 
     deps: [ConfigService], 
     multi: true 
    } 
] 
... 

但是,现在我想通过一个有效载荷到我的配置API,我必须从查询参数中读取。

我尝试以下,但它抛出

... 
@Injectable() 
export class ConfigService { 

    private _configData: any; 

    constructor(
     private _http: Http, 
     private _activatedRoute: ActivatedRoute 
) { 
} 
... 

如何读取APP_INITIALIZER服务内的查询参数?

+0

'APP_INITIALIZER'在应用程序启动前执行,Router尚未初始化。 [钩入Angular引导过程](https://blog.angularindepth.com/hooking-into-the-angular-bootstrap-process-36e82a01fba8)和[如何手动引导Angular应用程序](https:// blog。 angularindepth.com/how-to-manually-bootstrap-an-angular-application-9a36ccf86429)可能对你有帮助 –

回答

0
export class BootstrapService { 
    private getParameterByName(name) { 
    const url = window.location.href; 
    name = name.replace(/[\[\]]/g, '\\$&'); 
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), 
     results = regex.exec(url); 
    if (!results) return null; 
    if (!results[2]) return ''; 
    return decodeURIComponent(results[2].replace(/\+/g, ' ')); 
    } 

    public load(): Promise<void> { 
    const token = this.getParameterByName('token'); 
    // todo something with token 
    return Promise.resolve(); 
    } 
} 
+0

尝试给出一个完整的答案,而不是只是代码。它究竟做了什么?你能把它分解成更小的块吗? – JasonK

+0

这很简单;我们有一个名为getParameterByName的函数,它是vanilla javascript。 getParameterByName从当前URL返回查询参数 – user2798320

相关问题