我正在使用ngx-权限来处理Range6应用程序中的权限。在从端点检索数据之前,我想检查用户的权限。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权限来检查用户的权限,然后仍然返回一个可以观察到的组件?
发布于 2018-11-20 15:25:04
是的,为了记录起见,这是更一般的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
}https://stackoverflow.com/questions/53395616
复制相似问题