【发布时间】:2020-12-01 15:38:07
【问题描述】:
我需要直接浏览一个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")
}
}
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
当浏览到 /users/Jimmy 时,应用构造函数被调用,并重定向到默认值。删除 this.router.navigateByUrl("/default") 应该可以工作。