Angular 9 取消初始路径并重定向

问题描述 投票:1回答:1

我试图取消初始路径,例如:localhost:4200应该返回一个错误视图。相反,我希望我的主页只有当你导航到像localhost:4200tag1tag2时才可以访问。

我应该能够捕获给定的网址,并将其设置为主页。我已经尝试在app-routing模块中这样做,但我没有得到任何加载或错误说段不存在。

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {AppRoutes} from '../shared/globals/app-routes';
import {errorComponent} from '../errorComponent.ts'

export const tag1 = document.location.pathname.split('/')[1];
export const tag2 = document.location.pathname.split('/')[2];

const routes: Routes = [
  { path: 'tag1/tag2',
    loadChildren: () => import('../auth/auth.module').then(m => m.AuthModule) },
    { path: '',
    component: errorComponent    },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
javascript angular typescript angular-router
1个回答
1
投票

你的路由模块有一些错误。

  • 首先: tag1 还有... tag2 是变量。但你在路由中用的是字符串。应该是这样的。
path: `${tag1}/${tag2}`
  • 第二,你不需要在路由模块中直接获取url params。相反,你可以像下面这样做。
const routes: Routes = [
  { 
    path: '/:tag1/:tag2',
    loadChildren: () => import('../auth/auth.module').then(m => m.AuthModule) 
  },
  { 
    path: '',
    component: errorComponent    
  },
];

然后在你的 AuthPageComponent 你可以得到 tag1tag2 喜欢以下内容。

import { ActivatedRoute }  from "@angular/router";

constructor(
  private route: ActivatedRoute
) {
}

ngOnInit() {
  this.route.params.subscribe((params: { tag1: string, tag2: string }) => {
    console.log("tag1", params.tag1);
    console.log("tag2", params.tag2);
  })
}

更多信息,请参考官方文档。路线参数

© www.soinside.com 2019 - 2024. All rights reserved.