programing

각도 2 - 라우팅 - 관찰 가능한 작업을 활성화할 수 있음

telebox 2023. 7. 26. 21:48
반응형

각도 2 - 라우팅 - 관찰 가능한 작업을 활성화할 수 있음

CanActivate를 구현하는 AuthGuard(라우팅에 사용됨)가 있습니다.

canActivate() {
    return this.loginService.isLoggedIn();
}

문제는 CanActivate-result가 http-get-result에 의존한다는 것입니다. LoginServiceObservable을 반환합니다.

isLoggedIn():Observable<boolean> {
    return this.http.get(ApiResources.LOGON).map(response => response.ok);
}

백엔드 상태에 따라 CanActivate가 달라지도록 하려면 어떻게 해야 합니까?

# # # # # #

편집: 이 질문은 2016년에 나온 질문입니다. 각진/라우터의 매우 초기 단계가 사용되었습니다.

# # # # # #

"@angular/router"를 최신 버전(예: 3.0.0-alpha)으로 업그레이드해야 합니다.8"

AuthGuard.ts 수정

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private loginService: LoginService, private router: Router) {}

    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        return this.loginService
            .isLoggedIn()
            .map((e) => {
                if (e) {
                    return true;
                }
            })
            .catch(() => {
                this.router.navigate(['/login']);
                return Observable.of(false);
            });
    }
}

질문이 있으면 저에게 물어보세요.

연산자가 사용되지 않는 Angular 5+ 및 RxJS 5.5에 대한 Kery Hu의 답변 업데이트. 이제 catchError 연산자를 파이프 및 렛테이블 연산자함께 사용해야 합니다.

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { catchError, map} from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

@Injectable()
export class AuthGuard implements CanActivate {

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

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>  {
    return this.loginService.isLoggedIn().pipe(
      map(e => {
        if (e) {
          return true;
        } else {
          ...
        }
      }),
      catchError((err) => {
        this.router.navigate(['/login']);
        return of(false);
      })
    );
  }   
  
}

canActivate() 수락Observable<boolean>반환 가격으로가드는 관찰 가능한 항목이 해결될 때까지 기다렸다가 값을 확인합니다.'true'이면 검사를 통과하고, 그렇지 않으면(다른 데이터 또는 느려진 오류) 경로를 거부합니다.

사용할 수 있습니다..map변환 연산자Observable<Response>로.Observable<boolean>이와 같이:

canActivate(){
    return this.http.login().map((res: Response)=>{
       if ( res.status === 200 ) return true;
       return false;
    });
}

저는 이런 식으로 해왔습니다.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.userService.auth(() => this.router.navigate(['/user/sign-in']));}

보시다시피 userService에 폴백 함수를 보냅니다.auth http 호출이 실패할 경우 수행할 작업을 지정합니다.

userService에는 다음이 있습니다.

import 'rxjs/add/observable/of';

auth(fallback): Observable<boolean> {
return this.http.get(environment.API_URL + '/user/profile', { withCredentials: true })
  .map(() => true).catch(() => {
    fallback();
    return Observable.of(false);
  });}

이것은 당신에게 도움이 될 것입니다.

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { map, take } from 'rxjs/operators';
import { AuthState } from 'src/app/shared/state';

export const ROLE_SUPER = 'ROLE_SUPER';

@Injectable()
export class AdminGuard implements CanActivate {

    @Select(AuthState.userRole)
    private userRoles$: Observable<string[]>;

    constructor(private router: Router) {}

    /**
     * @description Checks the user role and navigate based on it
     */

    canActivate(): Observable<boolean> {
    return this.userRoles$.pipe(
        take(1),
        map(userRole => {
        console.log(userRole);
        if (!userRole) {
            return false;
        }
        if (userRole.indexOf(ROLE_SUPER) > -1) {
            return true;
        } else {
            this.router.navigate(['/login']);
        }
        return false;
        })
    );
    } // canActivate()
} // class

CanActivate는 Observable과 함께 작동하지만 CanActivate와 같이 두 번의 호출이 발생하면 실패합니다.[가드1, 가드2]
여기서 Guard1에서 False의 Observable을 반환하면 Guard2도 체크인하고 Guard2가 True를 반환하면 경로에 액세스할 수 있습니다.이를 방지하려면 Guard1에서 관찰 가능한 부울 대신 부울을 반환해야 합니다.

canActivate()에서 로컬 부울 속성을 반환할 수 있습니다(이 경우 기본값은 false).

private _canActivate: boolean = false;
canActivate() {
  return this._canActivate;
}

그런 다음 로그인 서비스 결과에서 해당 속성의 값을 수정할 수 있습니다.

//...
this.loginService.login().subscribe(success => this._canActivate = true);

언급URL : https://stackoverflow.com/questions/37948068/angular-2-routing-canactivate-work-with-observable

반응형