首页 > 解决方案 > 带有 ObservableInput 的 AngularFireAuth 错误

问题描述

我的 auth.service.ts 中有以下代码,这给了我以下似乎无法修复的错误:

代码

import { CanActivate, Router } from '@angular/router';
import {AngularFireAuth} from 'angularfire2/auth';
import { Injectable } from "@angular/core";
import { Observable, from } from "rxjs";

import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private auth: AngularFireAuth, private router: Router) {}

    canActivate(): Observable<boolean> {

      return from(this.auth)
        .take(1)
        .map(state => !!state)
        .do(authenticated => {
      if
        (!authenticated) this.router.navigate([ '/login' ]);
      })
    }

}

错误信息

ERROR in src/app/auth.service.ts(17,19): error TS2345: Argument of type 'AngularFireAuth' is not assignable to parameter of type 'ObservableInput<any>'.
      Property '[Symbol.iterator]' is missing in type 'AngularFireAuth' but required in type 'Iterable<any>'.

我错过了什么?

标签: angularrxjsangularfire2angularfire

解决方案


我认为您需要of操作员,该操作员会生成一个 Observable ,该 Observable 发出一次然后完成:

return of(this.auth)
  .map(state => !!state)
  .do(authenticated => {
    if (!authenticated) this.router.navigate([ '/login' ]);
  })

如果你升级到 RxJS 6,你需要pipe你的操作符:

return of(this.auth).pipe(
  .map(state => !!state),
  .tap(authenticated => {
    if (!authenticated) this.router.navigate([ '/login' ]);
  })
);

推荐阅读