使用activatedRoute访问Angular中的编码查询参数

时间:2017-11-18 14:28:18

标签: angular typescript angular2-routing

我有角度应用程序,从另一个应用程序重定向后加载。我想在身份验证网站返回我的Angular应用程序时访问查询参数。网址看起来像

http://localhost:4200/#/starterview?openId%3Dhttps:%2F%2Fmy.fidesque.net%2Fopenid%2Fyobtest_smeuser%26email%3Dyobtest@gml.nl%26userAuthMode%3DSP=

我想访问查询参数但我无法使用this.activatedRoute.snapshot.queryParams正确执行 我怀疑它是由于编码的参数。有没有解决方法?

的问候, Venky

2 个答案:

答案 0 :(得分:0)

我使用以下代码解码了URL。然后我可以正确地提取参数

const encodedUrl = 'http://localhost:4200/#/starterview?openId%3Dhttps:%2F%2Fmy.fidesque.net%2Fopenid%2Fyobtest_smeuser%26email%3Dyobtest@gml.nl%26userAuthMode%3DSP='
const decodedUrl = decodeURIComponent(encodedUrl);
console.log(decodedUrl);

答案 1 :(得分:0)

您可以使用Venky回答的encodeURIComponent解码编码的URL。如果您知道查询参数,并想从解码的URL中提取值。使用此功能:

getQueryParamFromMalformedURL(name) {
    const results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(decodeURIComponent(this.router.url)); // or window.location.href
    if (!results) {
        return 0;
    }
    return results[1] || 0;
}

如果网址为http://localhost:4200/login?username=jerry&code=1234,则

this.getQueryParamFromMalformedURL('username'); // should return 'jerry'