2017-03-15 65 views
0

如果有人可以幫助我,這將是非常感激。 firebase功能無法使用路由器。如何在火力點功能內使用路由器對象?

import { Component, OnInit } from '@angular/core'; 
import { FirebaseService } from '../../services/firebase.service'; 
import * as firebase from 'firebase'; 
import { Router } from '@angular/router'; 

@Component({ 
    selector: 'app-listings', 
    templateUrl: './listings.component.html', 
    styleUrls: ['./listings.component.css'] 
}) 

export class ListingsComponent implements OnInit { 
    listings: any; 
    constructor(
    private firebaseService: FirebaseService, 
    public router: Router 
) { 

這是firebase功能,我無法使用路由器。

firebase.auth().onAuthStateChanged(function(user) { 
     if (user) { 
     // User is signed in. 
     console.log('loggedIn'); 
     } else { 
     // No user is signed in. 
     console.log('not loggedIn'); 

控制檯似乎也正常工作。

 this.router.navigate(['/']); 
     } 
    }); 
    } 

    ngOnInit() { 
    this.firebaseService.getListings().subscribe(listings => { 
     this.listings = listings; 
     console.log(listings); 
    }); 
    } 

} 
+0

有什麼特別的原因,你正在使用的火力地堡SDK,而不是AngularFire的[鑑別](https://github.com/angular/angularfire2/blob /master/docs/5-user-authentication.md)? –

回答

0

嘗試使用箭頭功能來訪問this關鍵字。

firebase.auth().onAuthStateChanged(user => { 
    if (user) { 
     // User is signed in. 
     console.log('loggedIn'); 
    } else { 
     // No user is signed in. 
     console.log('not loggedIn'); 
     this.router.navigate(['/']); 
    } 
}); 

隨着AngularFire的認證......

constructor(
    private af: AngularFire, 
    private firebaseService: FirebaseService, 
    public router: Router 
) { 
    this.af.auth.take(1).subscribe(user => { 
     if (user) { 
      // User is signed in. 
      console.log('loggedIn'); 
     } else { 
      // No user is signed in. 
      console.log('not loggedIn'); 
      this.router.navigate(['/']); 
     } 
    }); 
} 
+0

謝謝@亞當。它正在工作! –

+0

順便說一句,不是AngularFireAuth的財產。它沒有它工作正常 –

+0

'import'rxjs/add/operator/take';'[take](http://reactivex.io/documentation/operators/take.html)將爲您管理訂閱。沒有它,你的訂閱將會持續。您必須手動取消訂閱,使用異步管道或像'take'這樣的操作員之一。 –