Angular 7路线保护不起作用

时间:2019-04-27 18:57:16

标签: angular typescript angular-routing angular-router-guards

我一直在尝试在Angular 7中进行路由保护,但是一直没有奏效。我尝试过的代码如下。谁能帮助我解决可能出现的问题?没有错误,但是我也没有得到想要的输出。输入用户名和密码后,我试图隐藏登录按钮。

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(['/']);
  }
}

标题组件

<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();
  }

}

1 个答案:

答案 0 :(得分:0)

有一些问题导致您的ngIf无法正常运行...

A)isLoggedIn是一个属性,而不是一个函数(您正在使用getter对其进行定义)。 B)isLoggedIn是一个可观察的属性,而不是布尔属性。....以下更改应隐藏该按钮。...

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