Aqeel
Aqeel

Reputation: 71

How to check if a user is logged-in in Angular 8

As a practice (following video tutorials from udemy) , I'm trying to Guard my link but it gives me some compilation error. Here's my auth-guard.service.ts:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
import 'rxjs/add/operator/map';

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

  constructor(private auth: AuthService, private route: Router) { }

  canActivate() {
    return this.auth.user$.map(user => {
      if (user) return true;
      this.route.navigate(['/login']);
      return false;
    })
  }
}

Here's my auth.service.ts

import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import 'firebase/auth';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  user$: Observable<firebase.User>;

  constructor(private afAuth: AngularFireAuth) { 
    this.user$ = afAuth.authState;
   }

  login() {
    this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
  }

  logout() {
    this.afAuth.auth.signOut();
  }
}

The compilation error I get from auth-guard.service.ts is "Property 'map' does not exist on type 'Observable'." Am I doing something wrong?

Upvotes: 5

Views: 12929

Answers (1)

Vikas
Vikas

Reputation: 12036

RxJS v5.5.2+ has moved to Pipeable operators to improve tree shaking and make it easier to create custom operators. now operators need to be combined using the pipe method
Refer This
New Import

import { map} from 'rxjs/operators';

Example

myObservable
  .pipe(filter(data => data > 8),map(data => data * 2),)
  .subscribe(...);

Modified Code

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
import { map} from 'rxjs/operators';

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

  constructor(private auth: AuthService, private route: Router) { }

  canActivate() {
    return this.auth.user$.pipe(map(user => {
      if (user) {return true;
       }else{
      this.route.navigate(['/login']);
      return false;}
    }))
  }
} 

Upvotes: 2

Related Questions