Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13733

this.router is undefined in AngularJS 2

Here is my method that registers a user and redirects to the main page:

onSubmit(){
    this.userService.createUser(this.user).subscribe(function (response) {
            alert('Successfully registered');
            localStorage.setItem('token', response['token']);
            this.router.navigate(['Home']);
        }, function (err) {
            console.log(err);
        }
    );
}

above it, I have this constructor:

constructor(private router: Router, private userService: UserService){}

I added ROUTER_PROVIDERS to the main component:

providers: [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS
]

When I try to register a user, I get this error:

TypeError: Cannot read property 'navigate' of undefined

What am I doing wrong?

Upvotes: 1

Views: 2024

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202196

You need to use arrow functions in your code to be able to use the "contextual this" (which corresponds to your component instance):

onSubmit(){
  this.userService.createUser(this.user).subscribe((response) => { // <---
        alert('Successfully registered');
        localStorage.setItem('token', response['token']);
        this.router.navigate(['Home']);
    }, (err) => { // <---
        console.log(err);
    }
  );
}

Upvotes: 5

Related Questions