从URL获取#access_token

时间:2017-09-12 11:23:19

标签: angular typescript angular-ui-router angular2-routing angular-router

SSO登录后的登陆网址为:

http://localhost:4200/login#access_token=f1946707a99f5be17cd639c49ed46e22af778a473aa1d93220d157d1a9b9ff83&token_type=bearer&expires_in=7200

现在,我如何从此网址中获取#access_token值?

1 个答案:

答案 0 :(得分:1)

使用下面提供的功能获取令牌值

//Get the Token value from URL
//You can use window.location.href or pass the value as you please
let token: string = getParameterByName("access_token", location.href);

public getParameterByName(name: string, url: string): string {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    let regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
}

如果您想要路由事件中的值

在导入路由器的组件

this.router.events
    .filter(event => event instanceof NavigationEnd)
    .map(() => this.activatedRoute)
    .map(route => {
        while (route.firstChild) route = route.firstChild;
        return route;
    }).filter(route => route.outlet === 'primary')
      .mergeMap(route => route.data)
      .subscribe((event) => {
          //Use the code here to get the value
       }
);