Henry Lau
Henry Lau

Reputation: 1

Cannot set property 'router' of undefined

I keep getting the following error when trying to navigate to "upload" page in Angular 2.

Cannot set property 'router' of undefined.

My Code:

import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router';
export class GameLandingComponent implements OnInit{
    ngOnInit(){
        //some codes and logics...
        this.router= Router;
        this.router.navigateByUrl('/upload');
    }
}

Appreciate if someone could give me some help.TIA.

Upvotes: 0

Views: 1082

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222722

You need to inject router inside the constructor and you are missing constructor Try this -

import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router';
export class GameLandingComponent implements OnInit{

    constructor(private router: Router){

    }

    ngOnInit(){

        this.router.navigateByUrl('/upload');
    }
}

Upvotes: 1

Khaled Ahmed
Khaled Ahmed

Reputation: 1134

it is not the way that you inject a class with inject it in the constructor

constructor(private router: Router){}
/// router now a private member of your class

Upvotes: 0

Related Questions