尝试router.navigate时未定义this.router [英] this.router is undefined while trying router.navigate

查看:107
本文介绍了尝试router.navigate时未定义this.router的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't get it why I get router undefined while trying a imperative navigation(if i write on the url, localhost:4200/alunos/1/edit it works fine). The error occurs when i call the editarContato method to navigate to a students detail page this is my detail class >

          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上编写,它也可以工作.

I printed aluno.id inside the method editarConsole as u can see, and it prints just fine... Also if I write on my browser localhost:4200/alunos/1/editar, it works.

推荐答案

您应在构造函数内部添加路由,否则未初始化

You should add route inside the constructor, otherwise its not initialized

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

然后

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

这篇关于尝试router.navigate时未定义this.router的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆