6

Below is my component. Point of error is the this.router.navigate() part. After login, I wanna redirect the user to a different page, something similar to $state.go('dashboard').

import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { AngularFire } from 'angularfire2';

@Component({
  templateUrl: 'app/auth/login.component.html'
})

export class LoginComponent {
  constructor(private af: AngularFire, private router: Router) { }
  onSubmit(formData) {
    if(formData.valid) {
      console.log(formData.value);
      this.af.auth.login({
        email: formData.value.email,
        password: formData.value.password
      }).then(function(success) {
        console.log(success);
        this.router.navigate(['/dashboard']);
      }).catch(function(err) {
        console.log(err);
        this.router.navigate(['/dashboard']);
      })
    }
  }
}

And I keep getting this error. Please enlighten me, what am I doing wrong?

enter image description here

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
KhoPhi
  • 9,660
  • 17
  • 77
  • 128

1 Answers1

16

You have to use Arrow function instead of function inside .then's success & catch callback's. Due to which inside success & catch callback function you're loosing component this(context).

Code

this.af.auth.login({
   email: formData.value.email,
   password: formData.value.password
}).then(
   //used Arrow function here
   (success)=> {
      console.log(success);
      this.router.navigate(['/dashboard']);
   }
).catch(
   //used Arrow function here
   (err)=> {
      console.log(err);
      this.router.navigate(['/dashboard']);
   }
)
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Thanks, really appreciate straightforward simple answers. Got it working now. I need to familiarize myself more with Typescript or es6 whatever these things are – KhoPhi Sep 24 '16 at 15:55
  • Instead of using arrow functions can you pass scope to to another function? Like in this situation, passing scope to this.handleError: .catch(this.handleError)? – Anthony Jul 11 '17 at 17:24
  • No.. then this.router will be unreachable.. we have to either use `arrow function` or `.bind(this)` – Pankaj Parkar Jul 11 '17 at 19:20
  • Aha.. never do that. Use arrow functions – Pankaj Parkar Oct 09 '18 at 04:38