0
votes

I am working on an Angular application implementing an AuthGuard class to avoid that a not logged user can access to a protected page. Following an online course I have done:

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']);

                             }
                           })
  }

}

And into my AuthService class I simply defined this property:

authInfo$:Observable<boolean>;

The problem is that into my AuthGuard class the IDE give me the following error on this line:

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

the error is:

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

And I can't understand why because, as you can see in my code, I have importend the import 'rxjs/add/operator/map' operator.

What is wrong? What am I missing? How can I fix this issue?

2

2 Answers

3
votes

You should add pipe .pipe(map()...)

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

                             }
                           })
                          ) // pipe ends
1
votes

In older code examples you still see rxjs flow like this:

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

However in more recent versions of rxjs you have to use operators in a pipe:

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

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