Angular 如何通过 HTTP Get 调用实现 CanActivate 防护

发布于 2025-01-15 06:55:58 字数 1594 浏览 2 评论 0原文

对于我的 Angular 6 项目,我们想使用 CanActivate 防护来检查授权。 为了实现这一点,我需要从 app.service 调用 getSummary() http get 调用,并从其响应中执行一些逻辑以提供授权。

逻辑如下

获取摘要。如果摘要项长度大于 1,则迭代并验证其激活状态。 如果激活状态不是活动并且没有返回摘要项,则将用户导航到登录页面

我有下面的服务 app.service.ts

@Injectable({
  providedIn: 'root'
})
export class ApiService {
 
 getSummary(url) {
    return this.http.get(url).pipe(
      retry(this.retryAttempts),
      map(data => {
        return data;
      }),
      catchError(err => {
        return this.handleError(err, url);
      })
    );
  } 
}

我有下面的 Auth Guard auth.guard.ts。我尝试实现如下所示的授权逻辑,但不确定如何返回 Observable。

export class AuthGuard implements CanActivate {
 
canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean>
{
    return this.checkAuthorization();
}

checkAuthorization():Observable<boolean>{

   let hasActiveSummary:boolean=false;
   this.apiService.getSummary(url)
      .subscribe( (data:any) => {

       console.log("Summary list:", data);
        if(data.length > 0){
          for (let i=0; i< data.length; i++) {
            if(data[i].activationStatus ==='ACTIVE') {
              hasActiveSummary=true;
              break;
            }
          }
        }
        console.log("STATUS",hasActiveSummary);
        if(!hasActiveSummary){
          this.router.navigate(['/login']);
        }
      },error => {
          console.log("Auth Guard error!", error);
        }
      );
} }

我对路由守卫很陌生。谁能指导如何以正确的方式实现这个场景?

For my Angular 6 project, we want to use CanActivate guard to check authorization.
To implement this, I need to call getSummary() http get call from app.service and perform some logic from its response to provide authorization.

The Logic goes as follows

Get the summary. If summary items length is more than one, iterate and verify its activation status.
If activation status is not Active and no summary items are returned then navigate the user to the login page

I have below service app.service.ts

@Injectable({
  providedIn: 'root'
})
export class ApiService {
 
 getSummary(url) {
    return this.http.get(url).pipe(
      retry(this.retryAttempts),
      map(data => {
        return data;
      }),
      catchError(err => {
        return this.handleError(err, url);
      })
    );
  } 
}

I have below Auth Guard auth.guard.ts.I have tried to implement authorization logic like below but am not sure how to return Observable.

export class AuthGuard implements CanActivate {
 
canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean>
{
    return this.checkAuthorization();
}

checkAuthorization():Observable<boolean>{

   let hasActiveSummary:boolean=false;
   this.apiService.getSummary(url)
      .subscribe( (data:any) => {

       console.log("Summary list:", data);
        if(data.length > 0){
          for (let i=0; i< data.length; i++) {
            if(data[i].activationStatus ==='ACTIVE') {
              hasActiveSummary=true;
              break;
            }
          }
        }
        console.log("STATUS",hasActiveSummary);
        if(!hasActiveSummary){
          this.router.navigate(['/login']);
        }
      },error => {
          console.log("Auth Guard error!", error);
        }
      );
} }

I am very new to routing guards. Can anyone guide how to implement this scenario in a correct way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柏拉图鍀咏恒 2025-01-22 06:55:58

您没有返回可观察的结果。

canActivate(): Observable
期望一个 Observable 的返回值(其他选项也是可能的 - 但在你的示例中 Observable 就可以了)。

const a = this.apiService.getSummary(url) 'a' 是一个 Observable

const b = this.apiService.getSummary(url).subscribe() 'b' 是订阅,而不是可观察的。

您需要做的是返回可观察值,如下所示。添加 pipe( map() ) 将保留 is 作为 Observable,但将内容“映射”为布尔值(在您的情况下),因此您将返回 Observable;

return this.apiService.getSummary(url)
      .pipe( 
          map(data:any) => {
             return true; // or false depending on your logic
          })
       )

You are not returning the observable.

canActivate(): Observable<boolean>
expects a return value of an Observable (other options are possible - but in your example an Observable is fine).

const a = this.apiService.getSummary(url) 'a' is an Observable

const b = this.apiService.getSummary(url).subscribe() 'b' is a Subscription, not an Observable.

What you need to do is return the observable as below. Adding the pipe( map() ) will keep is as an Observable, but 'map' the contents to be a boolean (in your case), so you will be returning Observable<boolean>

return this.apiService.getSummary(url)
      .pipe( 
          map(data:any) => {
             return true; // or false depending on your logic
          })
       )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文