Angular 6 - ERROR TypeError: "this.router is undefined"

Viewed 3702

Well, here i go again with more Angular problems. Sorry (?)

The thing is that i'm trying to redirect the user after a registration but for some reason, i'm getting the next error everytime:

ERROR TypeError: "this.router is undefined"

Basically, i'm handling the form submit (which works fine) inputs and posting them to my Laravel API, which takes it, executes the registration and returns a success message. Either way, i can't redirect the user (using Angular Router) using the next piece of code:

onSubmit() {
    this.authService.registerUser(this.user).subscribe(
      response => {
        let data = Object.assign(response.alert, this.denyControllConfig);
        this.sweetAlert(data);
      },
      error => {
        let data = {};
        let errors = error.error.errors;
        for (let key in errors) data[key] = errors[key][0];
        // this.sweetAlert(data);
      }
    );
    setTimeout(function () {
      this.router.navigate(['login']);
    }, 2000);
  }

I have imported the Rourter like this in the top of my file:

import { Router } from "@angular/router";

And this is my class constructor:

constructor(
    private router: Router,
    private authService: AuthService
  ) { }

Is there anything wrong with it ?

3 Answers

You need to use arrow functions in your code to be able to use the this

setTimeout(() => {
    this.router.navigate(['login']);
}, 2000);

I believe the problem is in the following code:

setTimeout(function () {
  this.router.navigate(['login']);
}, 2000);

In this case, since you are using anonymous function, the this keyword is the context of the function itself. To fix this, change it to:

setTimeout(() => {
   this.router.navigate(['login']);
})

The way arrow functions work, will allow this to be the class context instead of the function context.

Your setTimeout must use an arrow function as the callback to avoid re-binding the context of this.

Related