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

Angular 9 cancel initial path and redirect

我正在尝试取消初始路径,例如:localhost:4200/ 应该 return 一个错误视图。相反,我希望只有当您导航到 localhost:4200/tag1/tag2.

之类的内容时才能访问我的主页

我应该能够捕获给定的 url 并将其设置为主页。我曾尝试在应用程序路由模块中执行此操作,但没有加载任何内容或出现错误提示段不存在。

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 { }

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

  • 首先:tag1tag2是变量。但是你在路由中用作字符串。应该是:
path: `${tag1}/${tag2}`
  • 其次:不需要直接在路由模块中获取url参数。相反,您可以像下面这样:
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);
  })
}

更多信息请参考官方文档:Route Parameters