Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call.

 @Injectable()
 export class FeaturesLoadPermissionsService {
    permittedPefs = [];
    constructor() {       
       this.loadUserPefsService.getUserRolePefs(roleId)
                               .subscribe(
              (returnedListPefs) => {
                this.permittedPefs = returnedListPefs;
              },
              error => {
                console.log(error);
              });
    }
}

In another function, I am utilizing the same variable: permittedPefs.

However, since it starts off empty and gets populated at a delayed time, I need to wait for it before reusing it.

I attempted implementing async-await, where my objective is to ensure that permittedPefs has obtained an object value:

  async checkPefPresence(pefId) {
    const listPefs = await this.permittedPefs
  }

What steps should be taken to resolve this issue?

Answer №1

Storing the Observable returned by loadUserPefsService.getUserRolePefs method allows you to subscribe to it at a later time for access to user role permissions.

@Injectable()
export class FeaturesLoadPermissionsService {
    permittedPefs = [];
    constructor() {
        this.userRolePefsObservable = this.loadUserPefsService.getUserRolePefs(roleId);
    }
}

checkPefPresence(pefId) {
    let listPefs;
    this.userRolePefsObservable.subscribe(
        (returnedListPefs) => {
            listPefs = returnedListPefs;
        },
        error => {
            console.log(error);
        });
}

Answer №2

Utilize a behaviorSubject for managing permissions

  @Injectable()
    export class FeaturesLoadPermissionsService {

      permittedPefs: BehaviorSubject<any[]> = new BehaviorSubject([]);

      constructor() {
        this.loadUserPefsService.getUserRolePefs(roleId)
          .subscribe((returnedListPefs) => {
            this.permittedPefs.next(returnedListPefs);
          },
            error => {
              console.log(error);
            });
      }
    }

Then wherever you need to check for it (remember to unsubscribe when finished)

If it needs to be asynchronous, you can handle it like the example below

  async checkPefPresence(pefId): Promise {
    return new Promise((resolve, reject) => {
      this.featuresLoadPermissionsService.permittedPefs.subscribe(listPefs  => {
          //handle any necessary checks here 
          resolve();
      },reject);
    })

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

Utilize the <wbr> tag within FormattedMessage and assign it as a value while coding with TypeScript

Trying out the optional word break tag <wbr> in a message within <FormattedMessage id="some:message" />. Context Some words or texts are too lengthy for certain parent elements on smaller mobile screens, and we have a column layout t ...

Merge requirejs modules using build script

I am attempting to merge and compress require modules into a single file. For instance, if I have a file named article.js with the following content: define(["jquery","flexslider","share_div"],function(){}); I wish for all these dependencies to be merge ...

What is the most effective way to transmit a conditional operator via a TypeScript boolean field?

Currently, as part of my transition to typescript, I am working on incorporating a conditional operator into the table component provided by Ant Design. const paginationLogic = props.data.length <= 10 ? false : true return ( <> ...

Creating a dynamic sidebar menu with clickable submenus through jQuery and CSS for a user-friendly experience

<div id="sidebar" class="sidebar"> <div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 100%;"> <div data-scrollbar="true" data-height="100%" data-init="true" style="overflow: hidden; width: a ...

The function that iterates through the 'categoria' state and returns a new array is not functioning properly

Having difficulty with the object of a function using .map(). It works when the code is used directly, but not when put inside a function. For example: if(this.state.cat){ return _.map(this.state.cat, categoria => { if(this.state.search_ ...

Using ng-repeat in conjunction with ui-router conditions

Utilizing ui router ($routeprovider and $locationprovider) for angular js, I am looking to adjust the array being looped through in an ng-repeat based on the current url/route. Despite browsing similar threads on stack, I have not found a precise solution ...

Retrieving a dynamic JSON object for the MusicBrainz application using AngularJS

I want to incorporate a search form into my application that sends the form result to the specified link. I am retrieving artist names from the musicbrainz JSON database using the following request: "NAME OF AN ARTIST"%20e*&fmt=json The "NAME OF AN AR ...

HTML elements generated dynamically do not possess any jQuery properties

I have implemented a draggable list of Div elements using jQuery. Here is the code: <div id="external-events"> <h4>List Of Staffs</h4> <div class="external-event" data-id="1">Name</div> //Draggab ...

TypeScript: creating an interface property that relies on the value of another

Is it feasible to have an interface property that relies on another? For instance, consider the following: const object = { foo: 'hello', bar: { hello: '123', }, } I wish to ensure that the key in bar corresponds to the value of f ...

Dynamically allocate a controller to an element following the Bootstrap process

I have a unique AngularJS application that is initialized manually at a specific time. Later on, I need to display an HTML element without any ng-controller assigned to it. Is there a way to dynamically add an ng-controller to this element in order for it ...

Promise resolves prematurely before the completion of the process

Hey everyone, I'm working on a project that requires users to input their target URL for downloading and compressing images. Once the user provides the URL, the process begins downloading images asynchronously one by one into a directory. However, the ...

What types of modifications do ViewChildren and ContentChildren QueryLists keep an eye out for?

Imagine you come across the following lines of code: https://i.stack.imgur.com/7IFx1.png And then, in a different section, you stumble upon this code block: https://i.stack.imgur.com/qac0F.png Under what circumstances would () => {} be executed? Wha ...

How can we properly access the DOM element generated by an {#each} loop in Svelte when it is clicked?

Using Svelte's {#each} functionality, I am reactively loading elements in the following way: {#each $items as item} <div> <Button on:click={someFunction}>{item.text}</Button> (*) </div> {/each} (*) a component t ...

Vue.js mobile app may show a loaded DOM that remains invisible until the screen is tapped

I am facing a peculiar issue that has me stumped. On my mobile device, my page initially loads like this homepage However, once I tap the screen, all the components suddenly appear. Is there a way to simulate a click on my mobile? I'm struggling to u ...

What is the best way to retrieve ul li values using AngularJS?

I am looking to extract the content of li elements within a ul element in an AngularJS controller and save them into an array. Sample HTML Code: <ul id="list" my-directive> <li>A</li> <li>B</li> <li>C ...

What impact do Angular Signals have on RXJS Observables and how does this influence change detection within the framework?

As I transition to Signals in my Angular App, I am encountering challenges in identifying best practices and dealing with unexpected behaviors. Here is a snippet of my code which includes a userService and two Components: export class UserService { priva ...

Assigning a value to a variable from a method in Vue: a step-by-step guide

I'm having trouble assigning values from a method to variables in HTML. Here's what I have in my code: <b-card-text>X position {{xpos}}</b-card-text> <b-card-text>Y position {{ypos}}</b-card-text> I would like to assign v ...

React - The content of my JSON.String vanishes upon being placed inside a div element

My NFTDetails component includes a description from a JSON, which contains \n\n in it. Strangely, there are no new lines when I render the JSON value in a div, but when I log it to the console in Firefox, new lines appear. How can I make use of ...

Navbar Username in Next.js with Typescript and Supabase Integration

I'm currently facing an issue with retrieving the username of a user to display in my navbar. The desired username is stored in the "username" column of the table called "profiles" in my Supabase database. However, the data that's populating the ...

Altering the hover functionality for dynamically created class elements

I have a vision to create a unique e-commerce storefront with tile design, featuring an item thumbnail that reveals the item name upon hovering. I found inspiration from this example, but I want the item name to slide up smoothly on hover, rather than simp ...