1

I have been trying to work on route protecting in Angular 7 but it has not been working. The code that I have tried is given below. Can anyone help me with what might be going wrong? There are no errors, but i am not getting the desired output either. I am trying to hide the login button after the user enters the username and password.

auth.guard.ts

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

import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private authService: AuthService,
    private router: Router
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> {
    return this.authService.isLoggedIn
      .pipe(
        take(),
        map((isLoggedIn: boolean) => {
          if (!isLoggedIn){
            this.router.navigate(['']);
            // console.log("inside 29");
            return false;
          }
          this.router.navigate(['/search']);
          return true;
        });
      );
  }
}

auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
import { User } from '../Models/User/user';

@Injectable()
export class AuthService {
  private loggedIn = new BehaviorSubject<boolean>(false); // {1}

  get isLoggedIn() {

    return this.loggedIn.asObservable(); // {2}
  }

  constructor(
    private router: Router
  ) {}

  login(user: User){
    if (user.username !== '' && user.password !== '' ) { // {3}
      this.loggedIn=true;
      this.router.navigate(['/search']);
      console.log(this.loggedIn)

    }
  }

  logout() {
    this.loggedIn=false;
    this.router.navigate(['/']);
  }
}

header component

<li class="nav-item" *ngIf="IsLoggedIn()">
                    <a class="nav-link" (click)="openDialog()" >Login</a>
</li>


IsLoggedIn(): boolean {
     this.isLoggedIn = this.authService.isLoggedIn;
     return this.isLoggedIn;
 }

login.component.ts

import { Component, OnInit,Inject } from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import {HttpService} from '../../Services/Http/http.service'
import {CookieService} from 'ngx-cookie-service';
import { AuthService } from '../../auth/auth.service';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [AuthService]
})
export class LoginComponent implements OnInit {


  constructor(private authService:AuthService, private http:HttpService, private cookie:CookieService, public dialogRef: MatDialogRef<LoginComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { }

    loginModel:any = {username:'',password:''}
    loginResult:any = {}
    invalid:boolean = false;

  ngOnInit() {
    this.invalid = false;
  }

  login(){
    console.log(this.loginModel)
    this.http.validateUser(this.loginModel).subscribe(dataRes => {
      console.log(dataRes);
      this.loginResult = dataRes
      this.authService.login(this.loginModel);
      this.cookie.set('token',this.loginResult.token)
      this.invalid = false;
      this.dialogRef.close();
    },err => {
      this.invalid = true;
      this.loginResult = err
      console.log(err)
    });
  }

  closeDialog(){
    this.dialogRef.close();
  }

}
Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
Colleen
  • 63
  • 7

1 Answers1

0

There are a few issues that are preventing your ngIf from functioning correctly...

A) isLoggedIn is a property, not a function (you are defining it using a getter). B) isLoggedIn is an observable, not a boolean property..... the following change should hide the button....

<li class="nav-item" *ngIf="IsLoggedIn | async">
                <a class="nav-link" (click)="openDialog()" >Login</a>
</li>
  • Hello, thanks for your response - on introducing this, the login button disappears altogether. Any idea why this happens? – Colleen Apr 27 '19 at 19:35
  • @Colleen In your login function you set this.login equal to true, but this.login is a behaviorSubject.... try changing this.login = true to this.login.next(true) – Tzannetos Philippakos Apr 27 '19 at 19:51
  • Tried this, it's still giving me the same results – Colleen Apr 27 '19 at 19:58
  • @Colleen another thing I noticed is the logic is reversed.... You want to show the link when the user is NOT logged in, not the other way around.... try changing the ngIf to... *ngIf="!(IsLoggedIn | async)" – Tzannetos Philippakos Apr 27 '19 at 20:03