简体   繁体   English

如何在Angular 2中创建Singleton服务并读取URL Params

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

Im reading an url of the app http://localhost/?config=preprod 我正在阅读应用程序http:// localhost /?config = preprod的网址

Im trying to create a Singleton service which reads UrlParameters.js and exposes get(key) method. 我试图创建一个Singleton服务,它读取UrlParameters.js并公开get(key)方法。 Which stores config=preprod Similar below (from my Angular 1.x singleton service) 哪些商店config=preprod类似下面(来自我的Angular 1.x单件服务)

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. 现在,我想我也需要在Angular 2中访问此服务中的Route params,因为我无法在Angular 2中执行此操作。

Also, I need to share this UrlParams singleton with another Singleton service called Flag. 此外,我需要与另一个名为Flag的Singleton服务共享此UrlParams单例。 Which reads Flag.get('config') Something like below (extracted from my Angular 1.x project) Flag.js 其中读取Flag.get('config')下面的内容(从我的Angular 1.x项目中提取) Flag.js

set: function (flag) {
            if (UrlParameter.get(flag)) {
                localStorage.setItem(flag, UrlParameter.get(flag));
            }
        },
        get: function (flag) {
            return localStorage.getItem(flag);
        }

As suggested by @JordanFrankfurt I used Location service, and fits my purpose. 正如@JordanFrankfurt建议我使用位置服务,符合我的目的。 Also Thanks to @Günter Zöchbauer for the efforts. 还要感谢@GünterZöchbauer的努力。

Below is my UrlParams Service which is been also added in NgModule under providers 下面是它也被添加在NgModule下我UrlParams服务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; } } 

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

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. 我会尝试保持Angular 2约定,但如果你只想要一个你在Angular 2约定之外实例化的实例,那就非常简单了。

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 TypeScript版本

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM