【问题标题】:How to read query parameters in a APP_INITIALIZER service in angular4?如何在 angular4 中读取 APP_INITIALIZER 服务中的查询参数?
【发布时间】:2017-08-07 19:07:23
【问题描述】:

我写了一个ConfigService 以在 Angular 应用引导之前获取配置详细信息。

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

【问题讨论】:

标签: angular angular2-routing angular2-services angular-router


【解决方案1】:

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

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

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 好像是fairly well supported

【讨论】:

  • 经过几个小时的实验,您的回答解决了我的问题,谢谢!
【解决方案2】:
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();
  }
}

【讨论】:

  • 尝试给出完整的答案,而不仅仅是代码。它究竟是做什么的?你能把它分解成更小的块吗?
  • 这很简单;我们有一个名为 getParameterByName 的函数,它是 vanilla javascript。 getParameterByName 从当前 URL 返回查询参数
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多