Angular7等效于C#属性装饰器

时间:2019-06-20 09:51:41

标签: c# angular

我有一个带有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){
    ...
  }
}

2 个答案:

答案 0 :(得分:0)

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

使用装饰器的示例是组件

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

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

答案 1 :(得分:0)

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