Angular 6卫兵即使不发动也能阻挡

时间:2018-09-24 19:34:44

标签: angular typescript angular6 angular-router-guards

我在使用角度6路线防护系统时遇到问题。当我点击登录按钮时,它不会将我重定向到预期的路线。 我的html调用了login()函数,而在执行loginService.isAutenticated方法时true返回doLogin()时,它在守护程序本身中返回了false

loginComponent.ts

import { Component, OnInit } from '@angular/core';
import { User } from '../common/user.model';
import { LoginService } from './login.service';

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

  private usuario: User = new User();
  msg: string;

  constructor(private service: LoginService) { }

  ngOnInit() {
  }

  login() {
   this.service.fazerLogin(this.usuario);
  }

  limpar() {
    this.usuario.nome = '';
    this.usuario.senha = '';
  }

}

loginService.ts

import { Injectable } from '@angular/core';
import { User } from '../common/user.model';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';


@Injectable()
export class LoginService {

  url = 'api';
  constructor(private http: HttpClient,
              private router: Router
             ) { }

  isAuthenticated = false;

  doLogin(user: User) {

    if (user.name === 'admin' && user.pass === 'admin') {
      this.isAuthenticated = true;
      this.router.navigate(['/principal']);

    } else {
      console.log('Auth Failed');
    }
  }

  userIsAuthenticated() {
    return this.isAuthenticated;
  }
}

app.routes.ts

import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { PrincipalComponent } from './principal/principal.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { PendenciasComponent } from './pendencias/pendencias.component';
import { TesteComponent } from './teste/teste.component';
import { AuthGuard } from './guards/auth.guard';

const appRoutes: Routes = [
    { path: '', component: LoginComponent},
    { path: 'login', component: LoginComponent },
    { path: 'principal', component: PrincipalComponent,
      canActivate: [AuthGuard],
      children: [
        { path: 'pendencias', component: PendenciasComponent,
          canActivate: [AuthGuard]
        },
        { path: 'teste', component: TesteComponent,
          canActivate: [AuthGuard]
        },

      ]
    },
    { path: '**', component: PageNotFoundComponent },
  ];

export const routing = RouterModule.forRoot(appRoutes);

auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { LoginService } from '../login/login.service';

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

  constructor (private loginService: LoginService,
               private router: Router
              ) {}


  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | boolean {
      // if (this.loginService.usuarioEstaAutenticado()) {
      if (this.loginService.isAuthenticated) {
        console.log('canActivate retornou true');

        return true;
      }
      this.router.navigate(['/login']);
      console.log(this.loginService.isAuthenticated);

      console.log('canActivate retornou false');
      return false;

  }
}

1 个答案:

答案 0 :(得分:1)

如果您还需要将其注入到authguard中,则不要使该组件提供loginService。如果这样做,您的服务将不会单例,我想在这里您希望实例在组件和防护之间共享。设置模块提供的LoginService