TypeError:无法读取null Angular2 Router的属性'router'

时间:2016-09-24 15:28:36

标签: angular routing angular2-routing router angular2-router3

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

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

enter image description here

1 个答案:

答案 0 :(得分:12)

您必须在Arrow function function& .then内使用success代替catchsuccess回调。由于内部catch& 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']); } ) (上下文)。

<强>代码

Vue.directive('example', {
    params: ['a'],
    paramWatchers: {
        a: function (val, oldVal) {
            console.log('a changed!');
        }
    }
});
var vm = new Vue({
    el: '#app',
    data: {
        someValue: 1
    },
    methods: {
        change: function () {
            this.someValue += 1;
        }
    }
});