0

嘗試爲我的路由實現canActivate。登錄和連接到firebase是好的,但我嘗試使用下面的代碼canActivate和我不斷收到有關未解決的函數或方法map()的錯誤。我已確保一切正確導入。AngularFire/Firebase - AuthGuard未解析的函數或方法圖()

import 'rxjs/add/operator/do'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/take'; 

import { Injectable } from '@angular/core'; 
import { CanActivate, Router } from '@angular/router'; 
import { AngularFireAuth } from 'angularfire2/auth'; 
import { Observable } from 'rxjs/Observable'; 


@Injectable() 
export class AuthGuard implements CanActivate { 

constructor(private afAuth: AngularFireAuth, private router: Router) { 
} 

canActivate(): Observable<boolean> { 
return this.afAuth.authState 
    .take(1) 
    .map(authState => !!authState) 
    .do(authenticated => { 
    if (!authenticated) { 
     this.router.navigate([ '/error' ]); 
    } 
    }); 
} 
} 

AuthService.ts

import { Injectable } from '@angular/core'; 

import { AngularFireAuth } from 'angularfire2/auth'; 
import * as firebase from 'firebase/app'; 

import { Observable } from 'rxjs/Observable'; 

@Injectable() 
export class AuthService { 

    user: Observable<firebase.User>; 

    constructor(private firebaseAuth: AngularFireAuth) { 
    this.user = firebaseAuth.authState; 
    } 

    login(email: string, password: string) { 
    this.firebaseAuth 
     .auth 
     .signInWithEmailAndPassword(email, password) 
     .then(value => { 
     console.log('Logged in!'); 
     }) 
     .catch(err => { 
     console.log('Error while logging in!', err.message); 
     }); 
    } 

    logout() { 
    this.firebaseAuth.auth.signOut(); 
    } 
} 
+0

你在'app.module.ts'中註冊了嗎? – Hareesh

+0

AuthGuard位於提供程序數組中。 – Brns

+0

你的代碼對我來說很好,請查看這個[page](https://github.com/angular/angularfire2/issues/282)。 – Hareesh

回答

0

一兩件事我注意到你需要返回真或假的布爾函數

試試這個

canActivate(): Observable<boolean> { 
return this.afAuth.authState 
    .take(1) 
    .map(authState => !!authState) 
    .do(authenticated => !authenticated ? this.router.navigate(['/error']) : true); 
} 
0

既然你+ AngularFire是從rxjs/Observable導入Observable而不是'rxjs/Rx'以減少包的大小,您還需要導入您想要使用的RxJS操作員。

import 'rxjs/add/operator/map';