【问题标题】:Angular7 equivalent of C# attribute decoratorAngular7 等效于 C# 属性装饰器
【发布时间】:2026-01-19 03:00:02
【问题描述】:

我有一个带有 Authorize 属性的 api 方法来检查权限

[Authorize(ReadIndexes)]
public async Task<IActionResult> GetIndexes ()
{
  ...
}

是否有等效的方法来装饰 Angular 中的权限检查方法,这样如果权限不存在,则不会执行 api 调用

##????##
getIndexes(): Observable<Index[]> {
  // dont want to check in the method like below
  if(checkPerms("ReadIndexes")===true){
    ...
  }
}

【问题讨论】:

标签: javascript c# angular typescript ecmascript-6


【解决方案1】:

有装饰器,但你必须为装饰器编写逻辑

使用装饰器的示例是组件

@Component({
    selector: "thingy",
    template: `foo`
})
class MyComponent {
}

This 是一篇博客文章如何编写自定义装饰器

【讨论】:

    【解决方案2】:

    是的,您可以在 Angular 中使用 HttpInterceptor 来检查授权,例如

    import {Injectable} from '@angular/core';
    import {HttpInterceptor, HttpRequest, HttpHandler, HttpEvent} from '@angular/common/http';
    import {Observable, from} from 'rxjs';
    import {switchMap} from 'rxjs/operators';
    
    import {AuthService} from './auth.service';
    
    
    @Injectable()
    export class BearerInterceptor implements HttpInterceptor {
    
      constructor(protected authService: AuthService) {}
    
      public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return from(this.authService.isLoggedIn())
          .pipe(
            switchMap(isLoggedIn => {
              if (isLoggedIn) {
                return this.authService.addTokenToHeader(req.headers)
                  .pipe(
                    switchMap(headersWithBearer => {
                      const requestWithBearer = req.clone({headers: headersWithBearer});
                      return next.handle(requestWithBearer);
                    })
                  );
              }
    
              return next.handle(req);
            })
          );
      }
    }
    

    【讨论】: