7

below is my code for navigation

         export class AppComponent {
           router:Router
            doSwipe(direction: string){

               this.router.navigate(['/article']);
            }
       }

I am getting Cannot read property 'navigate' of undefined error.pls help to fix it

5 Answers 5

19

You need to inject the router, not just declare it as a property

constructor(private router: Router) {}
Sign up to request clarification or add additional context in comments.

Comments

2

In my case, I injected the router inside the constructor using the @Inject annotation.

constructor(@Inject(Router) private router: Router) {}

1 Comment

why we need this.is there any purpose of using @Inject(Router).Because without using this its working fine.is there any difference?
1

You need to inject Router in constructor:

export class AppComponent {
    constructor(
        private router: Router
    ) {}

    doSwipe(direction: string) {

        this.router.navigate(['/article']);
    }
}

Comments

0

You need to inject the router inside the constructor,

constructor(
     private router: Router
){

}

Comments

0

A bit old, but in my case I had Fabio answer, but forgot to add @autoInject()

so you have to add

import { autoinject } from 'aurelia-framework';

@autoinject()
export class YourClass {
     
     constructor(private router: Router) {}

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.