为什么我不能在可观察的内部使用switchMap

时间:2019-05-20 05:46:53

标签: angular firebase switchmap

enter image description here

我写了这个函数,

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不是函数。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

由于使用的是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

相关问题