首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在子路径之间进行安全和导航?

如何在子路径之间进行安全和导航?
EN

Stack Overflow用户
提问于 2020-09-07 06:48:22
回答 1查看 49关注 0票数 0

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

代码语言:javascript
运行
复制
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,
  },
];

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

因此,我试图在我的location.component中提交以下内容:

代码语言:javascript
运行
复制
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时,控制台中会出现以下错误:

代码语言:javascript
运行
复制
Error: Cannot match any routes. URL Segment: 'asporto; relativeTo = Route%28url: 'location', %20path:' location'%29'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-07 08:20:06

对于这个问题,您应该在您的CanActivate路径上使用Guard,并在其中使用locationService。所以做这样的事:

app.route.ts

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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;
     });
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63772598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档