Function that disregards the code block of 'return defer' in an observable manner

Lately, I've been delving into Angular 11 and attempting to create a function that verifies account permissions for a specific action based on changes in the SAS Token. Below are the functions I have implemented:

      /**
   * Verify if SAS has permissions
   * @param sasUri Sas address
   * @param permissions The permissions to verify
   * @returns Boolean Value
   */
  async hasPermissions(sasUri: string, permissions: SASInformationPermission[]): Promise<boolean> {
    const permissionAccount = await this.getSASUriInformation(sasUri).toPromise();
    return permissions.every((permission) => {
      permissionAccount.signedPermissions.includes(permission);
    });
  }

  /**
   * Get validation of action permission
   * @param sasUri Sas address
   * @param action The action to check
   * @returns Boolean value
   */
  hasActionPermission(sasUri: string, action: Action): Observable<boolean> {
    return defer(async () => {
      let permission: SASInformationPermission[];
      if (action === 'upload') {
        permission = [
          SASInformationPermission.Read,
          SASInformationPermission.List,
          SASInformationPermission.Write,
        ];
      } else {
        permission = [SASInformationPermission.List, SASInformationPermission.Read];
      }

      return await this.hasPermissions(sasUri, permission);
    });
  }

The "hasPermissions" function checks if the SAS has the necessary access rights for a specified action passed as a parameter. Conversely, the "HasActionPermission" function invokes the above function to obtain a Boolean value.

If the function "HasActionPermission" fails to enter the "return defer" block, what could be causing this issue?

Answer №1

Embrace using observables instead of promises. Switching between the two can be avoided, making your code more efficient. After calling hasActionPermissions(), feel free to use toPromise().

Here's a refactored version using only rxjs:

checkIfPermissionsExist(sasUri: string, permissions: SASInformationPermission[]): Observable<boolean> {
  return this.getSASUriInformation(sasUri).pipe(
    map(acct => permissions.every(x => acct.signedPermissions.includes(x)))
  );
}

checkAccessPermission(sasUri: string, action: Action): Observable<boolean> {
  const permission: SASInformationPermission[] = (action === 'upload') 
    ? [SASInformationPermission.Read, SASInformationPermission.List, SASInformationPermission.Write]
    : [SASInformationPermission.List, SASInformationPermission.Read];
    
  return this.checkIfPermissionsExist(sasUri, permission);
}

This approach is neater and will remain inactive until you call subscribe() or toPromise(), eliminating the need for defer().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Autocomplete feature in MUI allows filtering to begin after typing at least 3 characters

I've encountered an issue with the Autocomplete MUI component I'm using to filter a list of checkboxes. The popup with options should remain open at all times, but I only want the filtering to be triggered when the user input is more than 3 chara ...

Setting up Thrift in an Angular and Electron project

Attempting to incorporate Thrift API calls into my Angular application, I used the following command to generate client files: thrift-0.18.1.exe -r --gen js:ts <myService.thrift> The command successfully created both JavaScript (js) and TypeScript ( ...

Modeling with Nested Objects in TypeScript and Angular

ERROR: Unable to access 'applicants' property of undefined object When my component initializes, I am attempting to execute the following code: application: application; ngOnInit(): void { this.application.applicants[0].type = "1"; <-- T ...

What steps can be taken to resolve the TS2322 error that occurs while attempting to assign data[prop] to this

I am facing a problem with the code snippet below and need help resolving it. Can anyone provide guidance on how to fix this issue? type Data = { id: number, name: string } class Person { id: number name: string constructor(personData: Data) { ...

How to access global variables in Angular 2

Main.ts import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule); app.module.ts import { NgModule } from & ...

Eliminate the Material Stepper heading

Is there a way to remove the header navigation from the material stepper? I've tried using the following CSS code without success: .mat-horizontal-stepper-header-container{display: none} You can view the stepper on Stackblitz by clicking this link: ...

Tips for keeping a specific key value pair as the final entry in a Typescript Object

My goal is to construct a Typescript Object that has a specific element with the key 'NONE' always positioned at the end. This arrangement is crucial for displaying the object in my HTML page with this value appearing last. I am seeking an implem ...

Modify the "field" key type within the GridColDef interface of MUI DataGrid

Is there a way to assign an array of specific strings to the default type of GridColDef's field key, which is typically set to string? I attempted solutions like Array<Omit<GridColDef, 'field'> & {field: 'name' | &apo ...

Angular Material DatePicker: Day and Month selection without including the Year

Is there a way to customize an Angular Date Picker to show only Month and Day without the Year option? The provided link demonstrates a Month and Year picker, but I am looking to modify it for Month and Day selection. Changing YYYY to DD does not yield th ...

Tips for creating a jasmine test scenario for a function executed within the ngOnInit lifecycle hook

I am finding it challenging to create a successful test case for the code snippet below. In my component.ts file id = 123456; data = []; constructor(private serv: ApiService){} ngOnInint(){ getData(id); } getData(id){ this.serv.getRequest(url+id) ...

Typescript support on Emacs

"Is there a way to enable Typescript syntax highlighting in Emacs?" I have been struggling with this for quite some time. Using Emacs 24 on an Ubuntu Virtualbox VM, I can't seem to get package-refresh-contents to work as it just hangs on "Contacting ...

Issue with capturing events in Angular through emitting events

Apologies for my inexperience with Angular (V12), if I am not explaining my issue clearly. I am facing a problem with the $Event not capturing the custom object data emitted from another component. Upon setting up the function in the parent component, I en ...

Defining data types for an array of objects in a useState hook

I'm having trouble understanding the issue with my code. interface dataHistory { data: string, before: string | number, after: string | number, } I have an interface defined outside of the Functional Component and inside I specify its struct ...

Swapping Out Imports with Window Objects in TypeScript

After creating a TypeScript module that relies on a third-party library, the JavaScript output from compilation includes a statement using require: "use strict"; var dexie_1 = require("dexie"); var storage; (function (storage) { ... })(storage || (stora ...

The page remains static even after selecting a child route using routerLink in Angular 2

Hello, I am facing an issue that I need help with. I am using a routerLink to navigate to a child route in my Angular application. Although the URL changes as expected, the view does not update to display the component associated with the active child rout ...

Creating Multiple Promises in JavaScript: A Comprehensive Guide

How can I link multiple promises together? For example: var promise = new Promise(function(resolve, reject) { // Compose the pull url. var pullUrl = 'xxx'; // Use request library. request(pullUrl, function (error, response, bod ...

TypeScript has encountered an issue where a specific type A cannot be assigned to another type A, even though

Encountering a Typescript issue where it claims that type A is not compatible with type A, even though they are identical: Check out this playground link for the code snippet in context: declare interface ButtonInteraction { user: any; customId: strin ...

What is the best way to search for an Enum based on its value?

One of my challenges involves an enum containing various API messages that I have already translated for display in the front-end: export enum API_MESSAGES { FAILED_TO_LOAD = 'Failed to load data', TOKEN_INVALID = 'Token seems to be inva ...

How can data be accessed in an Angular 2 service the right way?

Currently, I have established a local instance of the service and am directly accessing data from it. I'm wondering if this approach is incorrect for a simple use case like sharing data between components. While trying to understand some fundamental n ...

Having trouble uploading files from Angular 8 to .NET Core 2.2?

Angular HTML : <input #file type="file" name="file" id="file" (click)="handleFileInput($event.target.files)" /> <input type="button" value="Save" (click) ="UploadForm()" /> Angular Code : this.formdata = new FormData(); this.formdata ...