6

下面是我的组件。错误点是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']);
      })
    }
  }
}

我不断收到这个错误。请赐教,我做错了什么?

在此处输入图像描述

4

1 回答 1

16

您必须使用Arrow function而不是functioninside .then's success& catchcallback's。由于哪个内部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']);
   }
)
于 2016-09-24T15:32:38.127 回答