gpt4 book ai didi

angular - 尝试 router.navigate 时 this.router 未定义

转载 作者:行者123 更新时间:2023-12-02 03:46:02 24 4
gpt4 key购买 nike

我不明白为什么在尝试命令式导航时路由器未定义(如果我在 url 上写入 localhost:4200/alunos/1/edit 它工作正常)。当我调用 editarContato 方法导航到学生详细信息页面时发生错误,这是我的详细信息类 >

          export class AlunoDetalheComponent implements OnInit {
router: Router;
aluno: any;
inscricao: Subscription;
constructor(
private route: ActivatedRoute,
private alunosService: AlunosService
) { }

ngOnInit() {
this.inscricao = this.route.params.subscribe(
(params: any) => {
let id = params['id'];

this.aluno = this.alunosService.getAlunoById(id);
}
)};

editarContato(){
console.log(this.aluno.id)
this.router.navigate(['/alunos',this.aluno.id,'editar']);
}
ngOnDestroy(){
this.inscricao.unsubscribe();
}
}

这是我设置路径的地方

  const alunosRoutes = [
{ path: 'alunos' , component: AlunosComponent, children: [

{ path: 'novo' , component: AlunoFormComponent},
{ path: ':id' , component: AlunoDetalheComponent},
{ path: ':id/editar' , component: AlunoFormComponent},

]}
];
@NgModule({
imports: [RouterModule.forChild(alunosRoutes)],
exports: [RouterModule]

}
)
export class AlunosRoutingModule{

}

我在 editarConsole 方法中打印了 aluno.id,如你所见,它打印得很好...此外,如果我在浏览器上写入 localhost:4200/alunos/1/editar,它也可以工作。

最佳答案

你应该在构造函数中添加路由,否则它不会初始化

constructor(
private router: Router,
private route: ActivatedRoute,
private alunosService: AlunosService
)

然后,

 this.router.navigate(['/alunos',this.aluno.id,'editar']);

关于angular - 尝试 router.navigate 时 this.router 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46744072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com