如何保护和在子路由之间导航?

How to secure and navigate between child routes?

我的 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 请求 returns true,在位置页面有一个输入框,用于检查客户的位置是否在进行交付的商店范围内,如果在范围内我必须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 路径上使用 CanActivate Guard,并在其中使用 locationService。所以做这样的事情:

app.route.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,
  },
];

location-guard.service.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;
     });
  }
}