Angular7 相当于 C# 属性装饰器



我有一个带有检查权限的授权属性的 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){
    ...
  }
}

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

使用装饰器的示例是组件

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

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

是的,您可以使用 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);
        })
      );
  }
}

最新更新