Angular如何将本地函数返回值与运行时回调http请求结合起来

发布于 2025-01-16 04:39:50 字数 2323 浏览 0 评论 0原文

我有本地函数来检查一些返回 true/false 的验证。我还有运行时回调函数,它是一个异步函数,即。 http 调用。

注意:此 checkPermission 函数发生在 for 循环内。

我想检查其他两个函数调用是否正确。谁能帮助我如何实现这一目标?

private checkPermissions(
        moduleId: number,
        permissions: number[],
        callback?: () => Observable<boolean>
    ): boolean {
        if(callback) {
            console.log('callback function defined');
        }

//以下是本地函数。如何在这里进行回调()?

        return this.userSecurityService.userHasLicenseAndPermission(
            moduleId,
            permissions
        );
    }

我的完整代码是: 组件:

options: NavOption[] = [];
this.options = this.sideNavService.loadMenus();

Sidenav 服务:

loadMenus(): NavOption[] {
    return this.getMenus();
}

private getMenus(): NavOption[] {
    const filteredMenuItems: NavOption[] = [];
    let menus =  [{
        id: 'recorded-events',
        label: 'Recorded events',
        icon: 'far fa-calendar-check fa-2x',
        url: `/incident/${this.organisationId}/list`,
        permissions: [
            EventReportingPermissions.View,
            EventReportingPermissions.ViewOwnEvents,
            EventReportingPermissions.ViewEmployeesEvents
        ],
        additionalPermissionCheck: () =>
            this.eventAccessGroupService.hasEventAccessGroupException()//this is the service to make http call
    },
    {
        id: 'new-events',
        label: 'Report new event',
        icon: 'far fa-calendar-plus fa-2x',
        url: `/incident/${this.organisationId}/create`,
        permissions: [EventReportingPermissions.Report]
    }]
    
    for(let item of menus) {
    
        let canAccess = this.checkPermissions(
                            topLevelItem.module,
                            subItem.permissions
                        );
        filteredMenuItems.push(item);
    }   
    return filteredMenuItems;
}

//local function

private checkPermissions(moduleId: number, permissions: number[]): boolean {
        //following returns value from local function and no http call
        return this.userSecurityService.userHasLicenseAndPermission(
            moduleId,
            permissions
        );
}

//additionalPermissionCheck?: () => Observable<boolean>;

I have local function to check some validation which returns true/false. I also have runtime callback function which is an async function ie. http call.

Note: This checkPermission function is happening inside a for loop.

I want to check if any othese two function call is true. Can anyone help me how to achieve this?

private checkPermissions(
        moduleId: number,
        permissions: number[],
        callback?: () => Observable<boolean>
    ): boolean {
        if(callback) {
            console.log('callback function defined');
        }

//following is the local function. how to make callback() here?

        return this.userSecurityService.userHasLicenseAndPermission(
            moduleId,
            permissions
        );
    }

My complete code is:
Component:

options: NavOption[] = [];
this.options = this.sideNavService.loadMenus();

Sidenav service:

loadMenus(): NavOption[] {
    return this.getMenus();
}

private getMenus(): NavOption[] {
    const filteredMenuItems: NavOption[] = [];
    let menus =  [{
        id: 'recorded-events',
        label: 'Recorded events',
        icon: 'far fa-calendar-check fa-2x',
        url: `/incident/${this.organisationId}/list`,
        permissions: [
            EventReportingPermissions.View,
            EventReportingPermissions.ViewOwnEvents,
            EventReportingPermissions.ViewEmployeesEvents
        ],
        additionalPermissionCheck: () =>
            this.eventAccessGroupService.hasEventAccessGroupException()//this is the service to make http call
    },
    {
        id: 'new-events',
        label: 'Report new event',
        icon: 'far fa-calendar-plus fa-2x',
        url: `/incident/${this.organisationId}/create`,
        permissions: [EventReportingPermissions.Report]
    }]
    
    for(let item of menus) {
    
        let canAccess = this.checkPermissions(
                            topLevelItem.module,
                            subItem.permissions
                        );
        filteredMenuItems.push(item);
    }   
    return filteredMenuItems;
}

//local function

private checkPermissions(moduleId: number, permissions: number[]): boolean {
        //following returns value from local function and no http call
        return this.userSecurityService.userHasLicenseAndPermission(
            moduleId,
            permissions
        );
}

//additionalPermissionCheck?: () => Observable<boolean>;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

赠意 2025-01-23 04:39:50

我不确定我是否理解正确,但是您的回调是执行权限检查的函数吗?

如果是这样,您可以使用 map 管道:

// Beware this returns Observable<boolean> and not boolean
const safeCallbackResult = callback ? callback() : of(true) // default to returning true as we'd like to check for the second condition
return callback().pipe(
  map(canDoAction => canDoAction ? this.userSecurityService.userHasLicenseAndPermission(...) : false)
)

如果您想返回布尔值,则不能。因为当您需要等待回调的可观察发射时,这是一个可能需要一些时间的操作。即使您可以使函数异步

private async checkPermissions(
  moduleId: number,  
  permissions: number[],
  callback?: () => Observable<boolean>
): Promise<boolean> {
  // callback().toPromise() if using RxJS 6
  // firstValueFrom(callback()) if using RxJS 7
  if(callback && ! (await callback().toPromise())) return false
  return this.userSecurityService.userHasLicenseAndPermission(...)
}

I am not sure I am understanding correctly but is your callback the function that performs the permission checking?

If so you can use a map pipe:

// Beware this returns Observable<boolean> and not boolean
const safeCallbackResult = callback ? callback() : of(true) // default to returning true as we'd like to check for the second condition
return callback().pipe(
  map(canDoAction => canDoAction ? this.userSecurityService.userHasLicenseAndPermission(...) : false)
)

If you'd like to return a boolean, you can't. Because the moment you need to await for the callback's observable emission that is an operation that can take some time. Even though you could make the function async

private async checkPermissions(
  moduleId: number,  
  permissions: number[],
  callback?: () => Observable<boolean>
): Promise<boolean> {
  // callback().toPromise() if using RxJS 6
  // firstValueFrom(callback()) if using RxJS 7
  if(callback && ! (await callback().toPromise())) return false
  return this.userSecurityService.userHasLicenseAndPermission(...)
}
故人如初 2025-01-23 04:39:50

像这样的:

sub = myHttpGetCall$().subscribe(value => {
        if (value && localValue) {
        // do whatever when both are true
        }
      }

其中 localValue 是本地函数的返回值,我认为这不是异步操作。

Something like this:

sub = myHttpGetCall$().subscribe(value => {
        if (value && localValue) {
        // do whatever when both are true
        }
      }

Where localValue is the return value from your local function, which I assume is not an async operation.

铃予 2025-01-23 04:39:50

使用 RxJs iif https://www.learnrxjs .io/learn-rxjs/operators/conditional/iif

booleanObservable$ = iif(() => yourLocalCondition, yourHttpRequest$, of(false));

如果你的 localCondition 为 true ,它将发出 http 请求,否则没有意义,所以它只是重新调整发出 false 的可观察量。

Use an RxJs iif https://www.learnrxjs.io/learn-rxjs/operators/conditional/iif

booleanObservable$ = iif(() => yourLocalCondition, yourHttpRequest$, of(false));

If your localCondition is true it will make the http request otherwise there is no point so it just retuns an observable that emits false.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文