Angular 5 canActivate всегда возвращаются на страницу входа для определенного маршрута - PullRequest
0 голосов
/ 27 августа 2018

Я пытаюсь защитить свое приложение от неавторизованных пользователей, определяя защиту маршрутов и назначая canActivate для каждого маршрута, который требуется защитить. На этих маршрутах все идет хорошо, например, когда кто-то хочет получить доступ к маршруту из URL, он будет автоматически перенаправлен на страницу входа, если только он не войдет в систему, тогда приложение перенаправит на определенный маршрут. Но есть один маршрут, когда пользователь входит в систему, он всегда возвращается на страницу входа. Эта проблема возникает на маршруте '/verify/:idC', что мне делать?

routing.ts:

{ path: 'verify/:idC', component: VerifyRoleComponent, canActivate: [AuthGuard] },

auth-guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

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

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : boolean {
    let url: string = state.url;

    return this.checkLogin(url);
  }

  checkLogin(url: string): boolean {
    if (this.authService.isLoggedIn) { return true; }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = url;

    // Navigate to the login page with extras
    this.router.navigate(['/login']);
    return false;
  }

}

auth.service.ts:

@Injectable()
export class AuthService {

  isLoggedIn = false;

  constructor() { }

  // store the URL so we can redirect after logging in
  redirectUrl: string;

  login(): Observable<boolean> {
    return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
  }

  logout(): void {
    this.isLoggedIn = false;
  }

}

проверить-component.ts:

@Component({
  selector: 'app-verify-role',
  templateUrl: './verify-role.component.html',
  styleUrls: ['./verify-role.component.scss']
})
export class VerifyRoleComponent implements OnInit {

  auth: Auth;

  constructor(private credService: CredentialService, private authService: AuthService,
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit() {    
    const id = this.route.snapshot.paramMap.get('idC');
    console.log(id) ;

    this.route.paramMap
      .switchMap((params: ParamMap) => 
        this.credService.getAccountId(params.get('idC')))
          .subscribe(res => {
            this.auth = res;
            console.log(this.auth);
            if (res.role.toString() == "User"){
              let idC = res.account;
              this.loginUser(idC);
            } else {}
          }, err => {
            console.log(err);
        });
  }

  loginUser(idC:string) {
    this.authService.login().subscribe(() => {
      if (this.authService.isLoggedIn) {
        let redirect = this.authService.redirectUrl ? this.authService.redirectUrl : '/profile/'+idC;
        this.router.navigate([redirect]);
      }
    });
  }

}

1 Ответ

0 голосов
/ 27 августа 2018

Я думаю, что вы должны добавить еще до this.router.navigate(['/login']);

...