AngularFire / Firebase - AuthGuard未解析的函数或方法映射()

时间:2017-11-18 13:55:21

标签: angular firebase firebase-authentication angularfire angularfire2

尝试为我的路线实施canActivate。登录和连接到firebase是好的,但我尝试使用下面的代码for 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();
  }
}

2 个答案:

答案 0 :(得分:0)

有一点我注意到你需要将true或false返回到布尔函数

试试这个

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

答案 1 :(得分:0)

由于你+ AngularFire正在从rxjs/Observable导入Observable而不是&#39; rxjs / Rx&#39;要减少包大小,您还需要导入要使用的RxJS运算符。

import 'rxjs/add/operator/map';