[英]How to read query parameters in a APP_INITIALIZER service in angular4?
我编写了一个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 服务中的查询参数?
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
}
}
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();
}
}
如果您想坚持使用 Angular 方式,我会说使用解析器。 在这里阅读更多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.