Angular Route Guard在刷新后保持在页面上



我的主页有一组项目,用户可以从中单击项目,这将把它们带到项目详细信息页面。从主页或详细信息页面,用户应该能够导航到第三个页面,其中包含特定于该项目的表单。

我已经设置了一个路由器保护,以防止用户在源页面不是前两个页面之一的情况下导航到此表单页面。如果试图从无效位置导航到表单页面,则用户将被路由到主页面。我的路由器防护在很大程度上起作用,但如果从表单页面刷新页面,用户会被踢回主页,这并不理想。如果用户已经在受保护的表单页面上,我如何让路由保护忽略页面刷新?

路由.guard.ts

class RoutingGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean | Promise<boolean> {
const currentUrl = this.router.url;
// The slice()s chop off the item ID so I can check the base url.
// Otherwise it'll mangle the url, which will fail the checks below
// and we'll end up with the default navigation, as desired.
const detailsUrl = currentUrl.slice(0, 20);
const formUrl = currentUrl.slice(0, 19);
// These checks (should) only allow access to the form page if
// coming from the details page or the main page (or, in theory
// the form page itself)
if(detailsUrl === '/main/details') return true;
// this is what doesn't work, because naturally the page refresh
// wipes out the url
if(formUrl === '/main/form') return true;
if(currentUrl === '/main') return true;
// Default: send the user back to the main page
return this.router.navigateByUrl('/main');
}
}

路由模块.ts中的路由

const routes: Routes = [
{
path: 'main',
component: MainComponent,
},
{
path: 'details/:id',
component: DetailsComponent,
},
{
path: 'form/:id',
component: FormComponent,
canActivate: [RoutingGuard],
},
];

路由器无法捕获以前的url。刷新后,将刷新所有数据。您必须将数据存储在Angular之外才能保存(例如sessionStorage(才能获取。然而,您的问题是,刷新后您仍然应该能够读取currentUrl。我想切片并没有达到你的预期。我觉得你切片有点太多了。检查切片内容是什么。尝试使用if(detailsUrl.includes('details')) return true;等,而不是使用===比较运算符

带路由器

previousUrl: string;
constructor(router: Router) {
router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
console.log('prev:', event.url);
this.previousUrl = event.url;
});
}

以下是一个示例:https://stackblitz.com/edit/angular-getting-previous-url-8ba1dh?file=src%2Fapp%2Fapp.component.ts

最新更新