Managing asynchronous variable assignment in Angular: tips and tricks

Within my Angular 6 application, there is a service where I declare a variable named "permittedPefs". This variable is asynchronously set within an httpClient.get call.

@Injectable()
    export class myService implements OnInit {

      permittedPefs = [];
      constructor(){}

      ngOnInit() {
      // STEP 1
      this.loadUserPefsService.getUserRolePefs(roleId).subscribe(
          (returnedListPefs) => {
            this.permittedPefs = returnedListPefs;
          },
          error => {
            console.log(error);
          });
      }
      // STEP 2
      this.myMethod(1);

Subsequently, a method is called that relies on the supposed value of "permittedPefs".

myMethod(pefId): boolean {
        return this.permittedPefs.includes(pefId);
}

The issue arises when it appears that "permittedPefs" has not yet been assigned a value, causing the method call to reference an incorrect value. How can this be resolved without necessitating a call from within the http Response callback (since it is used in multiple places)?

Any suggestions or solutions?

Answer №1

Dealing with Asynchronous Operations: It's highly recommended to use an Observable instead of a simple value

In your service :

fetchData (): Observable<any>{

return this.dataService.getData();

}

In your method :

 processId(id): boolean {

       this.someService.fetchData().subscribe(
       result => {

         if(result){
            return result.includes(id);
             }

        });

}

Answer №2

The reason for this occurrence is that your function is being invoked before the result is obtained. To resolve this, simply place the function call within the subscribe function.

Answer №3

To ensure the value of permittedPefs is set only after an asynchronous call is completed, make sure to call the method this.myMethod(1); within the subscription block.

ngOnInit() {
      // STEP 1
      this.loadUserPefsService.getUserRolePefs(roleId).subscribe(
          (returnedListPefs) => {
            this.permittedPefs = returnedListPefs;
           // STEP 2
           this.myMethod(1);  // Make sure to include this line
          },
          error => {
            console.log(error);
          });
}

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

Executing a JavaScript function across multiple elements: A step-by-step guide

I recently came across this code snippet on w3schools.com: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * {box-sizing: border-box} body {font-family: Verdana, ...

Exploring the integration of methods in Vue.js components

Within my Vuejs project, I developed a new form component and integrated it into the main index component. This new component needs to validate certain fields, with validation methods already created in the parent component. However, I am facing difficulti ...

"Three.js rendering issue: Particle sphere appearing as a straight line instead of a sphere

Exploring the world of THREE.js library has led me to attempt creating a particle sphere within my React App. Drawing inspiration from this project, I've made some progress but seem to have hit a roadblock. Strangely, despite similarities in code - e ...

Save room for text that shows up on its own

I am currently dealing with a situation where text appears conditionally and when it does, it causes the rest of the page to be pushed down. Does anyone know the best way to reserve the space for this text even when it's not visible so that I can pre ...

What is the best way to initialize an array with values in a Typescript constructor?

I've attempted the following: class PhraseService phrasePosShortNames: [{ id: number, name: string }]; phrasePosNames = [ { id: 0, longName: '#', shortName: '#' }, ...

Tips for utilizing dispatch within a client class?

As I continue my journey of developing a client/wrapper using axios with Zod and Redux, I aim to create a client that can handle fetch errors and dispatch necessary state updates to Redux. After successfully implementing Zod and the validation part into t ...

Ways to refresh the count of newly added div elements

Currently, I am working on a socket chat program that requires a badge to display the number of users in the chat room every time a new user joins. The code snippet provided below shows a function that adds the name of the new user to the list. The added n ...

Tips for accessing the app instance within a module in Nest.js

Currently, I am involved in a project that relies on multiple Nest repositories, approximately 4 in total. Each repository must integrate logging functionalities to monitor various events such as: Server lifecycle events Uncaught errors HTTP requests/resp ...

Converting an image to base64 format for storing in localStorage using Javascript

Currently, I am working on code that sets the background-image of a link. This is what I have so far: $("a.link").css("background-image", "url('images/icon.png')"); However, I want to enhance it by storing the image in localStorage: if (!local ...

Dealing with Cross-Origin Resource Sharing (CORS) issue in an Angular 6 and .Net Core

A project was recently completed involving the development of a .Net Core MVC (angular) app and a .net core Api app CORS has been enabled in both the Web app and API .Net Core services.AddCors(options => { options.AddPolicy("Cor ...

The value of req.user is not defined in a stack involving node, express, passport,

When I use console.log(req.session); I receive the message: Session {cookie:{ path: '/',_expires: null,originalMaxAge: null,httpOnly:true },passport: { user: 5b427a2d117d7c3f6087db8a } } However, when using console.log(req.user); I get un ...

NextAuth: JWT callback that returns an object

I've been working on a project using Next.js (11.1.2) + NextAuth (^4.0.5) + Strapi(3.6.8). The Next Auth credentials provider is functioning correctly. However, I need to access certain user information using the session. I attempted to do this by ut ...

A guide to creating animated mesh drawings using three.js

I have created a ribbon-like mesh using buffer geometry with invisible faces, and I am applying a custom shader to it: gl_FragColor = vec4(1.0, 1.0, 1.0, 0.0). Currently, as a 3D object moves along the ribbon, I perform raycasting to determine the index o ...

What is the process of defining a TypeScript AWS Lambda handler for Lambda Function URLs?

The npm package @types/aws-lambda provides TypeScript declarations for different ways Lambda functions can be triggered. For instance, when triggering the Lambda function through API Gateway, you can use the following code snippet: import { APIGatewayProxy ...

What is the most effective method for arranging divs in a horizontal layout?

When it comes to creating a horizontal three-column div layout, there are a variety of methods to consider: Position: relative/absolute; Float: left/right; with margin: 0 auto; for center div Float: left; for all divs Display table / table-cell What do ...

Ensure that the JavaScript file is fully loaded and that the JavaScript function has been properly initiated prior to executing any additional

Having an issue with a tracking code not working properly as it is called before a required JS script and function is loaded. The situation is as follows: Upon successful form submission (CF7 on WordPress), the following function is immediately called. ...

Deciphering the mechanics of collection referencing in mongoose

Today, I am delving into the world of using references in mongoose for the first time. I am trying to figure out how to save a template with a user ID. Do we need to retrieve the createdBy value from the client, or can it be inserted into the templateSchem ...

Send the JSON file to the server by uploading it

Situation Currently, I'm dealing with a page comprising questions structured as shown below: sections:[{ section: 1, questions:[{ question: 1, attachment: [FormData Object] ... }, { question: 2, ...

A guide on consolidating all app.use statements into a single shared file

My application's starting point, the index file, contains multiple instances of app.use. For example: app.use( if (!req.contextToken && req.contextTokenchecked) { req.queryToFirebase = false; req.contextTokenchecked = tru ...

Passing state updates between child components by utilizing the useReducer hook and dispatching actions

Check out this interactive example on CodeSandbox with the code provided and highlighted linting issues: https://codesandbox.io/s/react-repl-bw2h1 Here is a simple demonstration of my current project setup. In a container component, there is an important ...