2016-09-24 134 views
3

下面是我的組件。差錯點是this.router.navigate()部分。登錄後,我想將用戶重定向到其他頁面,類似於$state.go('dashboard')TypeError:無法讀取屬性'路由器'null Angular2路由器

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

回答

8

你必須使用Arrow function,而不是function.thensuccess & catch回調的內線。由於內部success & 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']); 
    } 
) 
+0

謝謝,真的很感謝直白簡單的答案。現在就開始工作了。我需要更多地熟悉Typescript或es6,無論這些東西是什麼 – Rexford

+0

@Rexford是啊,你會學習,因爲你的工作,謝謝:) –

+0

而不是使用箭頭函數可以將範圍傳遞給另一個函數?就像在這種情況下,將範圍傳遞給this.handleError:.catch(this.handleError)? – Anthony

相關問題