How to create Singleton service in Angular 2 and read URL Params
As suggested by @JordanFrankfurt I used Location service, and fits my purpose. Also Thanks to @Günter Zöchbauer for the efforts.
Below is my UrlParams Service which is been also added in NgModule under providers
url-parameter.service.ts
import { Injectable } from '@angular/core';import 'rxjs/add/operator/filter';import {LocationStrategy} from '@angular/common';@Injectable()export class UrlParameterService { public params = null; constructor(private location: LocationStrategy) {} get(key:string):String { debugger; if (!this.params) { this.params = {}; var queryString = this.location.path(); queryString.split('&').forEach((param) => { var val = (param.indexOf('?') ? param.slice(param.indexOf('?')+1).split('=') : param.split('=')); this.params[val[0]] = val[1]; }); } return this.params[key] || false; }}
I would try to stay within the Angular 2 conventions, but if you simply want an instance of something you've instantiated outside of Angular 2 conventions, it's pretty simple.
var UrlParameters = function() { this.instance = this; this.params = null; this.get = function(key) { if (!this.params){ params = {}; var queryString = window.location.search.substring(1); _(queryString.split('&')).each(function (param) { var val = param.split('='); params[val[0]] = val[1]; }); this.params = params; } return this.params[key]; }; this.set = function() { }}var Flag = { set: function (flag) { var urlParams = UrlParameter.getInstance(); if (urlParams.get(flag)) { localStorage.setItem(flag, UrlParameter.get(flag)); } }}
TypeScript version
class UrlParameter { static instance:UrlParameter; constructor() { UrlParameter.instance = this; } get( key: string) : string { // ... }}class Flag { set(key:string) : string { if (UrlParameter.instance.get(key)){ // you have it } }}
This might do what you want:
@Injectable() class MyService { constructor(router:Router) { this.router.events .filter(e => e instanceof NavigationEnd) .forEach(e => { var config = router.routerState.root.snapshot.param['config']; console.log(config); }); }}