【发布时间】:2018-05-02 04:30:35
【问题描述】:
尝试为我的路线实施 canActivate。登录和与 firebase 的连接都很好,但我尝试使用下面的代码进行 canActivate,但我不断收到有关未解析函数或方法 map() 的错误。我已确保所有内容都正确导入。
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中正确注册了吗? -
AuthGuard 在 providers 数组中。
-
你的代码在我看来没问题,检查一下page。
标签: angular firebase firebase-authentication angularfire angularfire2