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

问题描述 投票:2回答:2

我写的角度应用白手起家之前得到的配置细节ConfigService

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

...
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
2个回答
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();
  }
}

0
投票

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似乎fairly well supported

© www.soinside.com 2019 - 2024. All rights reserved.