3

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

以下代码编写在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 服务中的查询参数?

4

3 回答 3

6

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
    }
}

URL似乎得到了相当好的支持

于 2019-02-05T23:37:29.213 回答
3
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();
  }
}
于 2017-08-08T06:49:12.163 回答
1

如果您想坚持使用 Angular 方式,我会说使用解析器。在这里阅读更多

于 2020-09-09T07:58:19.833 回答