为什么我得到这个错误? 属性 'map' 在类型 'Observable<boolean>' 上不存在

Why I obtain this error? Property 'map' does not exist on type 'Observable<boolean>'

我正在开发一个 Angular 应用程序,该应用程序实现了 AuthGuard class 以避免未登录的用户可以访问受保护的页面。在我完成的在线课程之后:

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

import { AuthService } from './auth.service';
import 'rxjs/Rx';
import 'rxjs/add/operator/map'
import { Observable } from 'rxjs';

export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router:Router) {}

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

    return this.authService.authInfo$
                           .map(authInfo => authInfo.isLoggedIn())
                           .take(1)
                           .do(allowed => {
                             if(!allowed) {
                               this.router.navigate(['/login']);

                             }
                           })
  }

}

进入我的 AuthService class 我简单地定义了这个 属性:

authInfo$:Observable<boolean>;

问题是进入我的 AuthGuard class IDE 在这一行给我以下错误:

.map(authInfo => authInfo.isLoggedIn())

错误是:

Property 'map' does not exist on type 'Observable'.ts(2339)

我不明白为什么,因为正如您在我的代码中看到的那样,我导入了 import 'rxjs/add/operator/map' 运算符。

怎么了?我错过了什么?我该如何解决这个问题?

您应该添加 pipe .pipe(地图()...)

this.authService.authInfo$
                          .pipe(
                           map(authInfo => authInfo.isLoggedIn()),
                           take(1),
                           do(allowed => {
                             if(!allowed) {
                               this.router.navigate(['/login']);

                             }
                           })
                          ) // pipe ends

在较旧的代码示例中,您仍然会看到 rxjs 流程如下:

observable$
  .map(val => mapToSomething(val))

然而,在较新版本的 rxjs 中,您必须在管道中使用运算符:

// Make sure to import the operator!
import { map } from 'rxjs/operators';

observable$
  .pipe(
    map(val => mapToSomething(val))
)