代码之家  ›  专栏  ›  技术社区  ›  Fletch

ngxpermissions在角度6的可观察方法中具有权限检查

  •  1
  • Fletch  · 技术社区  · 6 年前

    我正在使用 ngx-permissions 处理Angular6应用程序中的权限。我想在从端点检索数据之前检查用户的权限。NGX权限提供了一种在方法hasPermission(PermissionName)中检查用户权限的方法。这将返回一个承诺。我想使用一个可观测的数据从端点检索数据,因为我已经读到了这是一种角度的方法。但是,我不知道如何将权限检查的承诺和可观察的方法结合起来。

    服务:

    getData(): Observable<Item[]<>>{
      this.permissionsService.hasPermission(Permission.CanViewData)
      .then(hasPermission => {
        if (hasPermission) {
          return this.http.get<Item[]>('http://endpoint/getdata', httpOptions).pipe(
            map(this.extractData), // this is calculated too late
            catchError(e => this.handleError(e, 'GetData', new Observable<Item[]>()))
          );
        }
      });
      return new Observable<Item[]>(); // this is always passed to the component
    }
    

    组件:

    getData(): void {
      this.service.getData().subscribe(data => {
        this.data = data
      });
    }
    

    我意识到我没有正确地调用hasPermission方法,因为我的代码总是进入最终阶段。 return new Observable<Item[]>(); . 但是,正在从我的端点检索数据-如果添加console.log,我可以看到 map(this.extractData) . 只是计算得太晚了。组件已继续,正在使用空的 Item[] .

    如何使用NGX权限中的permissionsService.hasPermission检查用户的权限,然后再尝试检索数据,并仍将可观测数据返回到组件?

    1 回复  |  直到 6 年前
        1
  •  0
  •   piotr szybicki    6 年前

    是的,而且记录在案的是更一般的RXJS问题。无论如何,你必须将承诺转换为可观察的,然后像这样链接调用:

    import { of, from, Observable } from 'rxjs'; 
    import { map, filter, flatMap } from 'rxjs/operators';
    
    class Caller {
    
      public constructor(){}
    
      public call() : Observable<Item[]> {
        //the promise returned from your method it has to be typed with boolean
        var permission = new Promise<boolean>(function(resolve, reject) {
          setTimeout(function() {
            resolve(true);
          }, 300);
        });
    
    
        //calling from(prommisse) converts promes to observable.\
        return from(permission)
        .pipe(
          filter(t => t), //just a trick to avoid if statemt in the flatMap call
          flatMap( t => {
            //call your http get method here
            var it:Item = {property: "1"};
            return of<Item[]>([it])
          }))
    
      }
    }
    
    export class Item {
      property: String
    }
    
    推荐文章