Angular 2 router queryParams are not added into url

為{幸葍}努か 提交于 2019-12-11 17:36:29

问题


I have an auth guard, which protects somes pages of my web-app. During the redirect i wanted to add queryParams to my url to allow user to come back to the site he want to pass. Code below was working for a few time. Today i realised that queryParms are not present in the url

async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
  let isLogged: boolean =  this.loggedInCustomer.isLoggedIn();
  if (!isLogged) {
    console.log(state.url);
    this.router.navigateByUrl(this.env.getLoginUrl(), { queryParams: {returnUrl: state.url}});
      return false;
    }
    return true;
 }

i've checked state.url it is correct. So the problem may be in creating router url.

I have made temporary solution

this.router.navigateByUrl(`${this.env.getLoginUrl()}?returnUrl=${state.url}`);

here is a link to similar problem Setting router queryParams in angular 2 do not work

But i know that it is not good. Can you please explain to me what am i doing wrong with this query? Why it stopped working? Regards!


回答1:


NavigateByUrl is always absolute Angular Doc's. Instead you can use navigate:

    let navigationExtras: NavigationExtras = {
      queryParams: { 'returnUrl': state.url },
      fragment: 'anchor'
    };

    this.router.navigate([this.env.getLoginUrl()], navigationExtras);


来源:https://stackoverflow.com/questions/48745224/angular-2-router-queryparams-are-not-added-into-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!