简体   繁体   中英

Cannot use map operator of rxjs in Angular project

I tried to use map operator of rxjs in my Angular project but error below occurs

ERROR in src/app/core/service/session.service.ts(88,9): error TS2552: Cannot find name 'map'. Did you mean 'Map'?

Am I missing anything?

Angular CLI 7.0.4

Node 10.13.0

rxjs 6.3.3

typescript 3.1.6

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';// This is where I import map operator
import { SessionService } from '../service/session.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private session: SessionService,
    private router: Router) {
  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> |boolean {
    return this.session
  .checkLoginState()//Returns an Observable of Session
  .pipe(
    map(session => {
      if (!session.login) {
        this.router.navigate(['']);
      }
      return session.login;
    })
   )
 }
}

My error happened, because I forget to check the imports of that functions, VS code always do it but sometimes not. Check if it's the same case, just add...

import { map, catchError } from 'rxjs/operators';

Map, Set, and Promise are ES6 features. In your tsconfig.json you are using:

"target": "es5" 

use

"target": "es6" 

or also you can try adding below line

"lib": ["es6"] 

avoid changing target because target is used to tell Typescript into which version of ECMAScript to compile your .ts files. Of course, you can change it, if the browser your application will be running in, will support that version of ECMAScript.

or simplest way would be installing

npm install --save-dev @types/core-js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM