如何在 angular4 中读取 APP_INITIALIZER 服务中的查询参数?

Gan*_*Gan 3 angular2-routing angular2-services angular angular-router

ConfigService在 angular 应用程序引导之前,我写了一篇文章来获取配置详细信息。

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

...
providers: [
    {
        provide: APP_INITIALIZER,
        useFactory: configServiceFactory,
        deps: [ConfigService],
        multi: true
    }
]
...
Run Code Online (Sandbox Code Playgroud)

但是,现在我想将有效负载传递给我必须从查询参数中读取的配置 API。

我尝试了以下但它抛出

...
@Injectable()
export class ConfigService {

    private _configData: any;

    constructor(
        private _http: Http,
        private _activatedRoute: ActivatedRoute
) {
}
...
Run Code Online (Sandbox Code Playgroud)

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

Eri*_*ndi 5

FWIW,window对象上已经提供了您需要的所有方法。

我最近不得不检查是否foo在 URL 上传递了一个查询参数。这是我最终做的:

export class ConfigService {
    constructor(/* your dependencies */) {
        // remember that your dependencies must be manually added
        // to your deps: [] property, ALL OF THEM (direct and indirect)
    }

    initialize() {
        // remember that constructors should not contain business logic
        // instead, call this during the APP_INITIALIZER part

        const url = new URL(window.location.href);
        const foo = url.searchParams.get('foo');

        // your business logic based on foo
    }
}
Run Code Online (Sandbox Code Playgroud)

URL似乎得到了很好的支持