Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Singleton service in Angular 2 and read URL Params

Im reading an url of the app http://localhost/?config=preprod

Im trying to create a Singleton service which reads UrlParameters.js and exposes get(key) method. Which stores config=preprod Similar below (from my Angular 1.x singleton service)

get: function (key) {
            if (!params) {
                params = {};
                var queryString = window.location.search.substring(1);
                _(queryString.split('&')).each(function (param) {
                    var val = param.split('=');
                    params[val[0]] = val[1];
                });
            }
            return params[key];
        }

Now, I think I also will need access to Route params inside this service in Angular 2, since I cannot do the in Angular 2.

Also, I need to share this UrlParams singleton with another Singleton service called Flag. Which reads Flag.get('config') Something like below (extracted from my Angular 1.x project) Flag.js

set: function (flag) {
            if (UrlParameter.get(flag)) {
                localStorage.setItem(flag, UrlParameter.get(flag));
            }
        },
        get: function (flag) {
            return localStorage.getItem(flag);
        }
like image 311
STEEL Avatar asked Mar 02 '17 06:03

STEEL


3 Answers

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

}
like image 100
STEEL Avatar answered Oct 07 '22 10:10

STEEL


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
        }
    }
}
like image 26
Derrick Avatar answered Oct 07 '22 10:10

Derrick


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);
    });
  }
}
like image 29
Günter Zöchbauer Avatar answered Oct 07 '22 10:10

Günter Zöchbauer