为什么我不能在 observable 中使用 switchMap

why i can't use switchMap inside observable

这个函数是我写的,

import { Alert } from './../classes/alert';
import { AlertService } from './alert.service';
import { AlertType } from './../enums/alert-type.enum';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { User } from '../classes/user';
import { Observable } from 'rxjs';
import { of } from 'rxjs';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from 
'@angular/fire/firestore';
import { switchMap } from 'rxjs/operators';

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

public currentUser: Observable<User | null>;

constructor(
private router: Router,
private alertService: AlertService,
private afAuth: AngularFireAuth,
private bd: AngularFirestore,
) {

this.currentUser = this.afAuth.authState
.switchMap((user) => {
  if(user){
    return this.bd.doc<User>(`users/${user.uid}`).valueChanges();
  } else {
     return of(null);
  }
  });
  }

但是控制台显示了这个错误,

this.afAuth.authState.switchMap is not a function.

我该如何解决这个问题?

由于您使用的是 RxJS v6+,因此您必须在 .pipe().

中调用运算符

例如:

// RxJS v6+
import { interval, fromEvent } from 'rxjs';
import { switchMap } from 'rxjs/operators';

fromEvent(document, 'click')
  .pipe(
    // restart counter on every click
    switchMap(() => interval(1000))
  )
  .subscribe(console.log);

有关详细信息,请参阅 documentation