【问题标题】:TypeError: Cannot read property 'router' of null Angular2 RouterTypeError:无法读取空 Angular2 路由器的属性“路由器”
【发布时间】:2016-09-24 15:28:35
【问题描述】:

下面是我的组件。错误点是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 routing angular2-routing router angular2-router3


    【解决方案1】:

    您必须在.thensuccesscatch 回调中使用Arrow function 而不是function。由于在 successcatch 回调 function 内部,您正在丢失组件 this(context)。

    代码

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

    【讨论】:

    • 谢谢,非常感谢简单明了的回答。现在可以工作了。我需要更多地熟悉 Typescript 或 es6,不管这些是什么
    • 你可以将作用域传递给另一个函数,而不是使用箭头函数吗?就像在这种情况下,将范围传递给 this.handleError: .catch(this.handleError)?
    • No.. 那么 this.router 将无法访问.. 我们必须使用arrow function.bind(this)
    • 啊哈..永远不要那样做。使用箭头函数
    猜你喜欢
    • 1970-01-01
    • 2018-10-17
    • 2015-05-25
    • 1970-01-01
    • 2020-05-22
    • 2017-11-20
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    相关资源
    最近更新 更多