嘗試爲我的路由實現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();
}
}
你在'app.module.ts'中註冊了嗎? – Hareesh
AuthGuard位於提供程序數組中。 – Brns
你的代碼對我來說很好,請查看這個[page](https://github.com/angular/angularfire2/issues/282)。 – Hareesh