3

AngularFire (2.0.0-rc.4)를 기다리는 Angular.js 2 (2.0.0-rc.4) (각도 cli로 작성)에 라우터 가드를 작성하려고합니다. 0-beta.2)를 사용하여 로그인 상태를 확인하고 사용자가 아직 로그인하지 않은 상태에서 (익명으로) 로그인합니다.AngularFire와 Angularjs에서 auth를 기다리는 라우트 가드 작성 2

내 가드 코드는 다음과 같습니다

canActivate() { 
    /* This part is to detect auth changes and log user in anonymously */ 
    this.auth 
     .subscribe(auth => { 
     if (!auth) { 
      this.auth.login(); 
     } 
     }); 

    /* This part is to listen to auth changes and IF there is an auth, resolves this guard with a true to let user in */ 
    return this.auth 
     .asObservable() 
     .filter(auth => { 
     return auth ? true : false; 
     }) 
     .map(x => { 
     console.log("TEST 1000"); 
     return true; 
     }); 
} 

내가 TEST 1000 콘솔 출력이 true 내 길을 돌아 canActivate()하는 것은 활성화되지 않음을 나타내는 표시에도 불구하고, 응용 프로그램을 실행합니다.

내 논리에 결함이 있다고 생각하거나 지능적으로 디버깅 할 수있는 멋진 아이디어가 있는지 궁금합니다.

답변

3

사용자가 관리자 인 경우 : 지금이 어떤 관련이 있는지

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


  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { 


    this.authService.admin().subscribe(

      res => { 

        // Navigate to the login page 

        if(!res) { 

          this.router.navigate(['/auth']); 

        } 

      }, 

      err => console.log(err), 

      () => { 

        // console.log('auth guard can activate complete') 

      } 

    ); 


    return this.authService.admin(); 

  } 

:

인증 서비스 :

import { Injectable } from '@angular/core'; 

import { Router } from '@angular/router'; 

import { AngularFire } from 'angularfire2'; 


import { Observable } from 'rxjs/Observable'; 

import { Subject } from 'rxjs/Rx'; 


@Injectable() 

export class AuthService { 


  admin$: Subject<boolean>; 


  private user: any = null; 


  constructor(private af: AngularFire, private router: Router) { 

    this.admin$ = <Subject<boolean>>new Subject(); 

    this.af.auth.subscribe(

      auth => { 

        if(auth){ 

          this.user = af.database.object(`users_list/${auth.uid}`).subscribe(

            res => { 

              this.user = res; 

              this.admin$.next(this.user.role === 10); 

              this.admin$.complete(); 

            }, 

            err => this.admin$.error(err) 

          ); 

        }else{ 

          this.router.navigate(['auth']); 

          this.admin$.next(false); 

          this.admin$.complete(); 

        } 

      } 

    ); 

  } 


  doLogin(credentials){ 

    this.admin$ = <Subject<boolean>>new Subject(); 

    this.af.auth.login(credentials); 

  } 


  admin() { 

    return this.admin$; 

  } 

} 

인증 가드 서비스 귀하의 질문에 complete()admin$에 전화하지 않고, 그것은 작동하지 않습니다. 콘솔은 true을 기록하지만 라우터는 다음 상태로 이동하지 않습니다.

나는 observables (따라서 구현이 잘못됨)를 꽤 많이 받고있다. 코드를 수정한다면, 훨씬 더 깨끗하고 아마 더 잘 보이기 때문에 나는 최종 결과를보고 싶다. 더 좋은 방법. 건배!

+0

당신이 옳습니다! 내 문제는 실제로, 그것은 완전하지 않았다. 나는'.asObservable()'을'take (1)'로 변경하여 하나의 값만을 기대하고 이후에 완료하면 작업을 시작했습니다! –

2

당신은이 문제

canActivate() { 

    this.auth 
     .subscribe(auth => { 
      if (!auth) this.auth.login() 
     }); 
    let authObs = this.auth 
     .asObservable() 
     .filter(auth => auth ? true : false) 
     .map(x => { 
      console.log("TEST 1000"); 
      return true; 
     }); 

    authObs.subscribe(a => return true); 

가 해결되는지 나는 문제가 경우에만 관찰을 만들고 실제로 가입하지 않았다고 생각 테스트 할 수 있습니다. CanActivate는 약속을 기대하거나 관찰 할 수없는 것을 부검합니다. 나는 현재 인증을 확인하고이를 사용하고

+0

안녕하세요 필립, 나는 이것을 시도했지만 불행히도'canActivate()'는'Observable '또는'boolean' 유형을 예상하고있어 컴파일되지 않았습니다. '내보내기 인터페이스 CanActivate { canActivate (경로 : ActivatedRouteSnapshot, 상태 : RouterStateSnapshot) : 관찰 가능 | 부울;}'는 cli의 기본 설정에 따라이 인터페이스가 최신 상태가되기를 기대합니다. –

+0

나는 angular.io에 대한 문서를 참조하고있었습니다. 내보내기 CanActivate (옵션 : CanActivateAnnotation) :(후크 : (다음 : ComponentInstruction, 이전 : ComponentInstruction) => 약속 | 부울). 너의 최신 정보는 내가 아는 최신 정보 일세. –

관련 문제