Angular2获取URL查询参数 [英] Angular2 get url query parameters

查看:443
本文介绍了Angular2获取URL查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Angular2网络应用程序设置一个Facebook注册. 一旦应用程序通过Facebook接受(重定向到Facebook授权页面后),它将使用令牌和代码作为url参数重定向到我的webapp:

I'm setting up a Facebook registration for my Angular2 web app. Once the application accepted via Facebook (after being redirected to the Facebook authorization page), it redirect to my webapp with the token and code as url params:

http://localhost:55976/?#access_token=MY_ACCESS_TOKEN&code=MY_CODE

但是,一旦页面被加载,参数将被删除.网址变为:

But once the page is loaded, the params are removed. The url become:

http://localhost:55976/

如何在删除参数(access_token和代码)之前提取它们? 我的路由配置包含:

How can I extract the parameters (access_token and code) before they are removed? My routing configuration contains:

{ path: 'login', component: LoginComponent },
{ path: 'login/:access_token/:code', component: LoginComponent },

这是我如何在我的login.component中重定向到Facebook: html:

Here is how I redirect to facebook in my login.component: html:

<a class="btn btn-social btn-facebook socialaccount_provider facebook" title="Facebook" href="#" (click)="login_facebook()">
    <span class="fa fa-facebook"></span> <span style="padding-left:25px">Sign in with Facebook</span>
</a>

打字稿:

login_facebook() {
    let url = 'https://www.facebook.com/dialog/oauth?'+
        'client_id=my_client_id' +
        '&redirect_uri=' + encodeURIComponent('http://localhost:55976/#/login/') +
        '&response_type=code%20token';
    console.log(url);
    window.location.href = url;
}

facebook api重定向到 http://localhost:55976/#/login/,是我尝试获取access_token和代码参数的地方.

The facebook api redirect to http://localhost:55976/#/login/, this is where I try to get the access_token and code parameters.

如果我删除了重定向网址中的尖锐字符,facebook将我重定向到正确的URL,但是如果没有尖锐的尖锐角度,我将无法解析该网址.

If I remove the sharp in the redirect url, facebook redirect me to the good URL, but without the sharp, angular cannot resolve the url.

在删除#"之前:

redirect_uri: http://localhost:55976/#/login/
facebook return: http://localhost:55976/?#access_token=MY_ACCESS_TOKEN&code=MY_CODE

删除#"后:

redirect_uri: http://localhost:55976/login/
facebook return: http://localhost:55976/login/?#access_token=MY_ACCESS_TOKEN&code=MY_CODE

这意味着问题出在犀利.但是没有尖锐的角度返回HTTP错误404.0-未找到.

That mean that the problem comes from the sharp. But without the sharp, angular returns HTTP Error 404.0 - Not Found.

推荐答案

这是我最终的工作代码:

Here is my final working code:

进口:

import { Router, NavigationCancel } from '@angular/router';
import { URLSearchParams, } from '@angular/http';

构造函数:

 constructor(public router: Router) {
    router.events.subscribe(s => {
      if (s instanceof NavigationCancel) {
        let params = new URLSearchParams(s.url.split('#')[1]);
        let access_token = params.get('access_token');
        let code = params.get('code');
      }
    });
  }

这篇关于Angular2获取URL查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆