2017-03-15 72 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'这样的操作员之一。 –