Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular RouterLink到动态创建路径的另一个组件_Angular - Fatal编程技术网

Angular RouterLink到动态创建路径的另一个组件

Angular RouterLink到动态创建路径的另一个组件,angular,Angular,我已经创建了UserComponent,该路由是: 应用程序路由.module.ts { path: ':username', component: UserComponent, children: [ { path: 'work-time', component: WorktimeComponent }, { path: 'absence', component: AbsenceComponent }, ], } 用户名是LoginCo

我已经创建了UserComponent,该路由是:

应用程序路由.module.ts

{
    path: ':username',
    component: UserComponent,
    children: [
      { path: 'work-time', component: WorktimeComponent },
      { path: 'absence', component: AbsenceComponent },
    ],
}
用户名是LoginComponent输入的值

问题是,当转到子组件路径(例如“localhost:4200/:username/work time”)并希望使用routerLink移回“localhost:4200/:username”时,它只显示主页面,该主页面是一个称为HomeComponent的独立组件

我试图用routerLink做的是:

user.component.html

<a routerLink=":username">
    <h1>test</h1>
</a>

测试

我想要的是创建一个routerLink,它将路由到例如“localhost:4200/peter”,但我真的不知道怎么做。

您必须从子组件中的路由参数获取用户名,并将该名称与链接绑定

import { ActivatedRoute } from '@angular/router';
public username: string;

constructor(private activatedRoute: ActivatedRoute) {
  this.activatedRoute.queryParams.subscribe(params => {
        this.username = params['username'];
    });
}

<a [routerLink]="username"></a>
从'@angular/router'导入{ActivatedRoute};
公共用户名:字符串;
构造函数(私有activatedRoute:activatedRoute){
this.activatedRoute.queryParams.subscribe(参数=>{
this.username=params['username'];
});
}

您试过了吗<代码>?是的,我试过了,但没用。我用
修复了它。这是一种不好的做法,还是我可以就这样离开呢?我还是建议你试试
。这不是一个坏习惯。只是代码看起来不错。