如何在子路线之间进行安全保护和导航



我的Angular应用程序中有以下route结构:

path: ':piva/:negozio',
component: NegozioComponent,
children: [
{
path: '',
component: ModuliComponent,
},
{
path: 'location',
component: LocationComponent
},
{
path: ':type',
component: ProductsComponent, 
//I can access this only if 'location' is true
},
{
path: 'item/:id',
component: ItemComponent,
},
];

因此,只有在location中.get请求返回true时,我才必须访问路径:type,在位置页面中有一个输入框,用于检查客户的位置是否在发货商店的范围内,如果在范围内,我必须将用户redirect连接到:type

因此,我试图在提交时在location.component中进行以下操作:

getLocation(): void {
this.locationService
.inRange(
this.addressComponent.geometry.location.lat(),
this.addressComponent.geometry.location.lng()
)
.subscribe((data: any) => {
if (data.inRange) {
this.router.navigate([
'asporto',
{ relativeTo: this.activatedRoute },
]);
}
});
}

但当我尝试提交button时,我在控制台中收到以下错误:

Error: Cannot match any routes. URL Segment: 'asporto; relativeTo = Route%28url: 'location', %20path:' location'%29'

对于此问题,您应该在:type路径上使用CanActivateGuard,并在其中使用locationService。所以这样做吧:

应用程序路由.ts

path: ':piva/:negozio',
component: NegozioComponent,
children: [
{
path: '',
component: ModuliComponent,
},
{
path: 'location',
component: LocationComponent
},
{
path: ':type',
component: ProductsComponent, 
canActivate: [locationGuard]
},
{
path: 'item/:id',
component: ItemComponent,
},
];

位置保护服务.ts

import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { LocationService } from './location.service';
@Injectable()
export class LocationGuard implements CanActivate {
constructor(public locationService: LocationService, public router: Router) {}
canActivate(): boolean {
this.locationService.inRange(
this.addressComponent.geometry.location.lat(),
this.addressComponent.geometry.location.lng()
.subscribe((data: any) => {
if (data.inRange) {
this.router.navigate([`/type`]);
return ture;
}
return false;
});
}
}

最新更新