尝试router.navigate时,this.router未定义

时间:2017-10-14 11:35:26

标签: angular

我不明白为什么我在尝试命令导航时得到路由器未定义(如果我在网址上写,localhost:4200 / alunos / 1 /编辑它工作正常)。当我调用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,它还可以。

2 个答案:

答案 0 :(得分:2)

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

pm.test("abc", function () {
    var jsonData = pm.response.json();
    var result = jsonData.result;
    var moid = result.'cluster.moid' ;
    pm.environment.set("clusterMoid", moid);
});

然后,

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

答案 1 :(得分:1)

您应该在构造函数中使用privatepublic编写路由器,然后它将自动初始化。