首页 > 解决方案 > NgxPermissions hasPermission 检查在 Angular 6 中的 Observable 方法中

问题描述

我正在使用ngx-permissions来处理我的 Angular 6 应用程序中的权限。我想在从端点检索数据之前检查用户的权限。ngx-permissions 在方法 hasPermission(permissionName) 中提供了一种检查用户权限的方法。这将返回一个承诺。我想使用 Observable 从端点检索数据,因为我已经读过这是 Angular 做事的方式。但是我不确定如何将权限检查中的 Promise 和 Observable 方法结合起来。

服务:

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 方法,因为我的代码总是落入 final return new Observable<Item[]>();。但是,正在从我的端点检索数据 - 如果我添加一个 console.log,我可以看到map(this.extractData). 只是计算得太晚了。该组件已经移动并正在使用空的Item[].

如何在尝试检索数据之前使用 ngx-permissions 中的 permissionsService.hasPermission 来检查用户的权限并仍将 Observable 返回给我的组件?

标签: angularobservable

解决方案


是的,为了记录,这是更一般的 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
}

推荐阅读