1

自从创建了一个新的 angular 6 项目以来,我复制的一些以前的代码似乎不起作用。这主要似乎是 rxjs 语法

.map上,它显示错误:

[ts] Property 'map' does not exist on type 'Observable'<User>'.

我似乎在另一个带有.take的文件上遇到了类似的错误

有人能指出我正确的方向来解决这个问题吗?

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router';

import { Observable } from 'rxjs';
import { AngularFireAuth } from 'angularfire2/auth';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/do';

@Injectable()

export class LoginGuardService implements CanActivate {

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


  canActivate(): Observable<boolean> {
    return this.auth.authState.map(authState => {
      if (authState) this.router.navigate(['/folders']);
      return !authState;
    }).take(1);
  }

}

第二后卫

canActivate(路由:ActivatedRouteSnapshot,状态:RouterStateSnapshot):

Observable<boolean> {

    this.authGuardStateURL = state.url;

    return this.auth.authState.pipe( 
      take(1)
      .map(authState => !!authState)
      .do(auth => !auth ? this.router.navigate(['/login']) : true)
    )

  }
4

1 回答 1

0

我认为您使用 Angular CLI 来创建您的应用程序。Angular 6 随 RxJS 6 一起提供,从 v5 开始,RxJS 一直在使用可管道操作符。

所以你的代码应该是这样的:

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AngularFireAuth } from 'angularfire2/auth';
import { map, take, tap } from 'rxjs/operators';

@Injectable()

export class LoginGuardService implements CanActivate {

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

  canActivate(): Observable<boolean> {
    return this.auth.authState.pipe(
      map(authState => {
        if (authState) this.router.navigate(['/folders']);
        return !authState;
      }),
      take(1)
    )
  }

  //Second Guard

  canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot): Observable<boolean> {

      this.authGuardStateURL = state.url;

      return this.auth.authState.pipe(
        take(1),
        map(authState => !!authState),
        tap(auth => !auth ? this.router.navigate(['/login']) : true)
      )
   }
}

注意你现在是如何导入操作符的,以及你是如何放置map方法takepipe

于 2018-07-09T11:37:42.857 回答