我如何在firebase函数中使用路由器对象?

时间:2017-03-15 18:17:33

标签: angular2-routing angularfire2

如果有人能帮助我,我将不胜感激。我无法在@NgModule({ declarations: [ HomeComponent, DialogOverviewExampleDialog // HERE ], entryComponents: [ DialogOverviewExampleDialog // AND HERE ], ... 函数中使用路由器。

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

1 个答案:

答案 0 :(得分: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(['/']);
        }
    });
}