以下是我的组件。错误点是this.router.navigate()部分。登录后,我想将用户重定向到另一个页面,类似于$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']);
      })
    }
  }
}

而且我不断收到此错误。请赐教,我在做什么错?

angular - TypeError : Cannot read property  'router'  of null Angular2 Router-LMLPHP

最佳答案

您必须在Arrow functionfunction.then回调的内部使用success而不是catch。由于在successcatch回调function中存在哪个内容,因此您失去了this组件(上下文)。

代码

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']);
   }
)

10-07 19:35
查看更多