Angular - 直接浏览路线

Angular - Browse route direct

我需要直接浏览一个URL并传递一个值,例如localhost:4200/vip/mycode,然后这将直接转到默认页面。

我的 routing.module.ts 设置如下:

const routes: Routes = [
  { path: 'enroll', component: EnrollComponent },
  { path: 'default', component: DefaultComponent },
  { path: 'aboutus', component: AboutusComponent },
  { path: 'overview', component: OverviewComponent },
  { path: 'contactus', component: ContactusComponent },
  { path: 'vip/:code', component: VipComponent },

];

vip.component.ts 文件如下:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';

@Component({
  selector: 'app-vip',
  templateUrl: './vip.component.html',
  styleUrls: ['./vip.component.css']
})
export class VipComponent implements OnInit {
  public code: string;
  public APIresult: any;
  constructor(
    private _route: ActivatedRoute,
    private _router: Router,
  ) { 
    
    this._route.params.subscribe((params: Params) => {
      this.code = params.code; 
      if (this.code != null) {
        sessionStorage.setItem('code', this.code);
        alert(this.code)
      }
    })
    
  }

  ngOnInit(): void {
  }
}

但是我在浏览时无法正常工作localhost:4200/vip/mycode

当我这样做时,它只会将我带到默认组件。

这是我的 app.component.ts:

从“@angular/core”导入{组件}; 从“@angular/router”导入{路由器};

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Website';
  
  constructor(
    private router: Router,
  ){  
    this.router.navigateByUrl("/default")
  }
}

如有任何帮助,我们将不胜感激。谢谢

您还应该将其添加到路由数组,以便它被重定向到默认值。

{ path: '', redirectTo: 'default', pathMatch: 'full' },