Cannot read property 'navigate' of undefin

2020-07-16 06:45发布

问题:

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

回答1:

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

constructor(private router: Router) {}


回答2:

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

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


回答3:

You need to inject Router in constructor:

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

    doSwipe(direction: string) {

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


回答4:

You need to inject the router inside the constructor,

constructor(
     private router: Router
){

}