0

我在使用 Angular 6 路由保护时遇到问题。当我点击登录按钮时,它不会将我重定向到预期的路线。我的 html 调用该login()函数,而在执行该方法时返回,它loginService.isAutenticated在警卫本身中返回。truedoLogin()false

登录组件.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 = '';
  }

}

登录服务.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;
  }
}

应用程序.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;

  }
}
4

1 回答 1

1

如果您还需要将 loginService 注入到 auth guard 中,请不要让组件提供 loginService。如果你这样做,你的服务将不是单例的,我认为你希望实例在组件和警卫之间共享。制作 Module 提供的 LoginService

于 2018-09-24T19:49:11.770 回答