【问题标题】:AngularFire/Firebase - AuthGuard unresolved function or method map()AngularFire/Firebase - AuthGuard 未解析的函数或方法 map()
【发布时间】: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


【解决方案1】:

由于你 + AngularFire 是从 rxjs/Observable 导入 Observable 而不是 'rxjs/Rx' 以减小包大小,因此你还需要导入你想要使用的 RxJS 运算符。

import 'rxjs/add/operator/map';

【讨论】:

    【解决方案2】:

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

    试试这个

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

    【讨论】:

      猜你喜欢
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 2022-12-03
      • 2014-03-01
      • 1970-01-01
      相关资源
      最近更新 更多