我有一个带有Ionic web组件的StencilJS应用程序,使用以下路由设置:
<ion-router useHash={false}>
<ion-route url="/home" component="page-home"/>
<ion-route url="/login" component="page-login"/>
<ion-route url="/main" component="page-main">
</ion-router>当我收到来自api的401错误时,我希望重定向到登录页面,并将当前url作为重定向querystring参数(以便将用户重定向回原来的位置),如下所示:
const navCtrl: HTMLIonRouterElement = document.querySelector("ion-router");
fetch('https://someapi.com/users/1').then(
res => navCtrl.push('/main'),
err => navCtrl.push(`/login?redirect=${window.location.pathname}`)
);当我这样做时,我从应用程序接口收到一个错误,我想导航到当前路由作为查询字符串参数的登录页面,模板抛出以下错误:[ion-router] the path does not match any route。
如何将querystring与ion-router一起使用?
发布于 2020-06-06 00:32:53
IMO它目前是离子领域的一个bug (见https://github.com/ionic-team/ionic/issues/19707)。
为了暂时解决这个问题,您可能可以使用
navCtrl.push('/login');
history.replaceState(undefined, '', `?redirect=${window.location.pathname}`);发布于 2020-06-06 15:02:55
感谢您在正确方向上的推动!您提供的代码没有更改url,因为navCtr.push返回一个promise。您必须等待它完成,然后才能更改状态。我最终得到了这个变通方法:
const navCtrl: HTMLIonRouterElement = document.querySelector("ion-router");
fetch('https://someapi.com/users/1').then(
res => navCtrl.push('/main'),
err => {
navCtrl
.push(`/login`)
.then(() => history.replaceState(undefined, '', `?redirect=${encodeURIComponent(window.location.pathname)}`))
}
);奇怪的是,像离子和模板这样被广泛使用的框架并不支持常见的查询字符串。我希望他们能尽快解决这个问题。
发布于 2021-01-15 19:29:06
我构建了一个本机函数来从querystring中获取每个参数,
export const RouterGetUriParam = (name) => {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
if (urlParams.has(name)) {
return urlParams.get(name);
} else {
return null;
}
};你可以像这样在模具中使用它:
@Prop() withMore: boolean = (RouterGetUriParam("withMore") == 'true')urlparam看起来像?withMore=true
https://stackoverflow.com/questions/62214428
复制相似问题