2017-12-11 11 views
1

목표 :Guard를 사용하여 Angular Material Dialog의 입력을 기반으로 URL을 보호하려면 어떻게합니까?

가드를 사용하여 특정 URL을 보호했습니다. 사용자가 해당 URL에 액세스하려고하면 Angular 4 재질 대화 상자가 열립니다. 대화 상자 입력을 기반으로 사용자 권한을 부여하거나 승인하지 않겠습니다.

문제 : 대화에 가입 가드에서

. 닫으면 대화 상자가 나타납니다. 사용자가 URL에 액세스하려고하면 canActivate는 사용자 입력을 기다리지 않고 자동으로 false로 평가됩니다. 즉, 모달이 가입되어 있지만 함수가 대화 상자가 닫힐 때까지 대기하지 않으므로 false가 즉시 반환됩니다.

질문 :

가 어떻게 사용자 입력에 따라 URL에 대한 사용자 권한을 부여 권한을 부여하거나 할 수?

가드 :

@Injectable() 
    export class VerificationGuard implements CanActivate { 

     pwd: string; 
     auth: boolean; 

     constructor(private dialog: MatDialog) { 
     } 

     public canActivate() { 
     const dialog = this.dialog.open(VerificationDialogComponent); 
     dialog.afterClosed() 
      .subscribe(val => { 
      if (val) { 
       this.pwd = val; 
       return true; 
      } 
      }); 
     return false; 
     } 
    } 

대화 상자 :

import { Component, OnInit } from '@angular/core'; 
    import { MatDialogRef } from '@angular/material'; 

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

     pwd: string; 

     constructor(public dialogRef: MatDialogRef<VerificationDialogComponent>) { } 

     ngOnInit() { 
     } 

     /** 
     * Close dialog and pass back data. 
     */ 
     confirmSelection() { 
     this.dialogRef.close(this.pwd); 
     } 
    } 
+0

왜 콜백 안에'false'가 반환되지 않습니까? 또한'subscribe'에서 돌아 오지 않고'map'을 대신 사용할 수 있습니다. – Alex

+0

콜백에서 false가 반환되지 않습니다. 또한 구독을 매핑 할 수 없습니다. – jinan

+0

'작동하지 않음'은 무엇을 의미합니까? 글쎄, 아마 작동하지 않습니다, 당신이 구독에서 돌아 오려고하는 것은 불가능합니다. – Alex

답변

1

대신 VerificationGuard에서이 모달을 여는, 플래그를 저장하는 서비스를 사용하는 것이 좋습니다.

@Injectable() 
export class AuthService { 
    isLoggedIn = false; 
} 

서비스는 사용자를 로그인하지 않지만 사용자의 인증 여부를 알려주는 플래그가 있습니다.

당신의 가드에서 전화 : 라우터 탐색 이벤트가 방출되는 위치에 모달 논리를 할 의향

@Injectable() 
export class VerificationGuard implements CanActivate { 

    constructor(private authService: AuthService) {} 

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { 
    return this.authService.isLoggedIn) 
    } 
} 

, 그것은 자격 증명 제출에 다음을 수행 있습니다 AuthService.isLoggedIn

  1. 설정을 ~ true.
  2. 라우터 탐색 이벤트를 내 보냅니다.
  3. 가드에서 AuthService.isLoggedIn ~ false으로 설정하십시오.

AuthService.isLoggedIn은 false로 재설정해야하고 canActivate()은 true를 반환해야합니다.

비슷한 예를 보려면 "Teach AuthGuard to authenticate"에서 https://angular.io/guide/router#canactivatechild-guarding-child-routes을 참조하십시오.