如何检查用户是否已在Angular 8中登录

问题描述 投票:0回答:2

作为一种实践(来自udemy的视频教程之后),我正在尝试保护我的链接,但这会给我一些编译错误。这是我的auth-guard.service.ts:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
import 'rxjs/add/operator/map';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {

  constructor(private auth: AuthService, private route: Router) { }

  canActivate() {
    return this.auth.user$.map(user => {
      if (user) return true;
      this.route.navigate(['/login']);
      return false;
    })
  }
}

这是我的auth.service.ts

import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import 'firebase/auth';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  user$: Observable<firebase.User>;

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

  login() {
    this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
  }

  logout() {
    this.afAuth.auth.signOut();
  }
}

我从auth-guard.service.ts收到的编译错误是“类型'Observable'不存在属性'map'。”我做错什么了吗?

angular
2个回答
0
投票

RxJS v5.5.2+已移至Pipeable运算符,以改善树抖动并使其更易于创建自定义运算符。现在需要使用operators方法合并pipe Refer This新导入

import { map} from 'rxjs/operators';

示例

myObservable
  .pipe(filter(data => data > 8),map(data => data * 2),)
  .subscribe(...);

修改的代码

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
import { map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {

  constructor(private auth: AuthService, private route: Router) { }

  canActivate() {
    return this.auth.user$.pipe(map(user => {
      if (user) {return true;
       }else{
      this.route.navigate(['/login']);
      return false;}
    }))
  }
} 

0
投票

Observable.map自RXJS 5.x起不存在。相反,尝试使用Observable.pipe代替:

user$.pipe(map(user => { 
 return ...
}))
© www.soinside.com 2019 - 2024. All rights reserved.