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

What could be causing the issue with my validation for alphabetical input?

I am currently working on a registration form that only accepts alphabetical input. However, I am facing an issue where my error message appears regardless of whether I input an alphabetical or special character. According to my understanding, the code sho ...

Using Symbol.iterator in Typescript: A step-by-step guide

I have decided to upgrade my old React JavaScript app to React Typescript. While trying to reuse some code that worked perfectly fine in the old app, I encountered errors in TS - this is also my first time using TS. The data type I am exporting is as foll ...

Implementing auto-complete functionality for a text box in an MVC application using jQuery

After incorporating code for auto completion in a text box using AJAX results, the following code was utilized: HTML: <div class="form-group col-xs-15"> <input type="text" class="form-control" id="tableOneTextBox" placeholder="Value" > ...

What is the best way to display only a specific container from a page within an IFRAME?

Taking the example into consideration: Imagine a scenario where you have a webpage containing numerous DIVs. Now, the goal is to render a single DIV and its child DIVs within an IFrame. Upon rendering the following code, you'll notice a black box ag ...

Divergence in results: discrepancy found in the outputs of nodejs crypto module and tweetnacl.js

Consider this code snippet in nodejs: import crypto from 'crypto'; const pkey = `-----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIJC52rh4PVHgA/4p20mFhiaQ/iKtmr/XJWMtqAmdTaFw -----END PRIVATE KEY-----`; // placeholder key function sign_message(m ...

The Vue property I customized in my component is not being recognized by VSCode(Vetur)

I've successfully implemented a plugin in Vue by declaring it in a main.ts file, defining its type in a plugin.d.ts file, and utilizing it in a component.vue file. Although the compilation is error-free, I am encountering an issue with VSCode intellis ...

Exploring Angular 2's @Input and @Output Directives

I'm unsure about whether I should be using @Input and @Output. From my understanding, these decorators are typically used when you want to establish communication between a parent and child component. Can you confirm or correct me on this? I have 3 c ...

Ways to verify the nodemon version that is currently installed on your local machine

On my Windows 10 machine, I recently installed nodemon locally in a project and now I'm curious to know which version is installed. Can someone please share the command to check the version of nodemon without needing to install it globally? My aim is ...

Exploration of frontend utilization of web API resources

I've come across this issue multiple times. Whenever I modify a resource's result or parameters and search for where it's utilized, I always end up overlooking some hidden part of the application. Do you have any effective techniques to loc ...

Having trouble displaying the Primevue dialog modal in Vue 3?

I am using [email protected] and [email protected] Main script import { createApp } from 'vue' import App from './App.vue' import router from './router' import PrimeVue from 'primevue/config'; import &apos ...

Having trouble connecting to the Brewery API, could use some guidance from the experts (Novice)

I'm currently facing some difficulties connecting to a brewery API (). I am developing a webpage where users can input the city they are visiting and receive a list of breweries in that city. As someone unfamiliar with APIs, I am unsure about the nece ...

When passing an invalid value to the Props in TypeScript, no errors are being thrown

const enum ColumnValues { one = 1, two = 2, three = 3, } interface Props { style?: StyleProp<ViewStyle>; title?: string; titleContainerStyle?: StyleProp<ViewStyle>; titleStyle?: StyleProp<TextStyle>; textInputStyle?: Styl ...

jQuery: event not firing for dynamically loaded elements via AJAX

In my jQuery/HTML5 front-end setup (with backend-generated code omitted), I am currently using version 1.8.3 of jQuery with no version conflicts. The front-end calls the following functions: detailAjaxCall("\/client\/orders\/detailsLoad&bso ...

Exploring the power of AngularJS in manipulating Google Maps polygons with the help of ng-repeat

I recently started using a Google Maps plugin specifically designed for AngularJS, which can be found at . My goal is to display polygons on the map, so my HTML code looks something like this: <google-map center="map.center" zoom="map.zoom" draggab ...

Transfer the controller of the parent directive to a directive controller, similar to how it is executed in the "link" function

In the structure of my directives, there is a need for one directive to have functions in its controller so that child elements can interact with it. However, this directive also needs access to its parent directive's controller. I am unsure of how to ...

Trouble transferring $rootScope.currentUser between AngularJS profile and settings page

I am in the process of setting up a site using Angular, Express, Node, and Passport. Currently, I am configuring Angular to monitor the $rootScope.currentUser variable with the following code: app.run(function ($rootScope, $location, Auth) { // Watch ...

Determine the generic types of callback in TypeScript based on the argument provided

There are numerous Stack Overflow questions that share a similar title, but it seems none of them address this particular inquiry. I'm in the process of developing a wrapper for an express RequestHandler that can catch errors in asynchronous handlers ...

Preventing dragging in Vis.js nodes after a double click: a definitive guide

Working with my Vis.js network, I have set up an event listener to capture double clicks on a node. ISSUE: After double-clicking a node, it unexpectedly starts dragging and remains attached to the mouse cursor until clicked again. How can I prevent this b ...

Transitioning from using a jQuery get request to utilizing Vue.js

Looking to transition from JQuery-based js to Vue as a newcomer to JavaScript. Seeking guidance on making a get request and displaying the retrieved data. What approach would you recommend for this task? Here's the HTML snippet: <div> <di ...

How to remove the border of the MUI Select Component in React JS after it has been clicked on

I am struggling to find the proper CSS code to remove the blue border from Select in MUI after clicking on it. Even though I managed to remove the default border, the blue one still persists as shown in this sandbox example (https://codesandbox.io/s/autumn ...