Delay the HTTP request in returning its response

I am facing an issue with handling a HTTP GET request to retrieve permission data. This request is used in my auth.service.ts file within the isProjectLead() function. I need to ensure that access to a certain page is granted only after the HTTP request has returned the necessary value.

Can anyone suggest how I can achieve this? I attempted using Promises, but I lack expertise in this area.

get isProjectLead() {

  var flag = false;
  //var thisPromiseCount = ++this.promiseCount;

  var user = JSON.parse(localStorage.getItem("user"));
  if (!this.selectedProject) {
    this.selectedProject = parseInt(this.route.snapshot.paramMap.get('id'));
  }

  this.linkService.getLinksByUserAndProject(user.username, this.selectedProject).subscribe(links => {
        this.links = links;

        this.links.forEach(element => {
          if (JSON.parse(element).role.id == "2") {
            flag = true;
          }
        });
      },
        (err: any) => {
        });


  return flag;
}

Answer №1

Converting Observables into Promises

async checkIfProjectLeader() {

  var isLeader = false;
  //var thisPromiseCount = ++this.promiseCount;

  var user = JSON.parse(localStorage.getItem("user"));
  if (!this.selectedProject) {
    this.selectedProject = parseInt(this.route.snapshot.paramMap.get('id'));
  }

  try {
    var linksData = await this.linkService
      .getLinksByUserAndProject(user.username, this.selectedProject)
      .toPromise();
    this.links = linksData;

    this.links.forEach(link => {
      if (JSON.parse(link).role.id == "2") {
        isLeader = true;
      }
    });

  } catch (error) {
    // handle error
  }

  return isLeader;
}

Important Note

The returned response will also be in the form of a promise, so you must wait for the promise to be resolved.

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

Utilizing Checkboxes for Filtering Mat-Table Data in Angular 8

I've been attempting to implement checkbox filtering for a table, but none of my attempts have been successful so far. Here is a snippet of my table structure: <mat-table [dataSource]="dataSource" [hidden]="!show" matSort > <!-- Locat ...

Challenges with using async await alongside synchronous functions

I'm currently navigating through a library that utilizes async functions and feeling a bit overwhelmed. I'm attempting to call a function that should return a string, but I'm hitting some roadblocks. As I understand it, the ZeroEx library fu ...

Retrieving rows from a MySQL table that contain a specified BIGINT from an array parameter

I've encountered a problem with mysql while using serverless-mysql in TypeScript. It seems like my query might be incorrect. Here is how I am constructing the query: export default async function ExcuteQuery(query: any, values: any) { try { ...

Problem with dynamic page routes in Next.js (and using TypeScript)

Hi everyone, I'm currently learning next.js and I'm facing an issue while trying to set up a route like **pages/perfil/[name]** The problem I'm encountering is that the data fetched from an API call for this page is based on an id, but I wa ...

The performance of linting has significantly decreased following the upgrade of nx/angular, particularly for the plugin import/no-deprecated

The upgrade process of the project involved moving from version 11.2.11 to version 12.2.10 through the nx upgrade process (nx migrate) Following this upgrade, the code linting process now takes around 4 minutes, compared to the previous 30 seconds: time ...

What could be causing TypeScript to identify my immer draft as undefined?

I'm completely lost, can someone please help me with this issue: Currently, I am trying to update a typed configuration. Within my Provider component: const [data, setData] = useImmer<typeof INITIAL_CONFIG>(INITIAL_CONFIG) ... function updateF ...

@Viewchild doesn't have access to matSort

In my Angular project, I am having trouble getting my @ViewChild instance to work with MatSort in HTML. component.ts file: import { MatSort } from '@angular/material'; export class MyComponent { @ViewChild(MatSort) sort: MatSort; } ngOn ...

The transformation from className to class attribute does not occur for custom elements in JSX

I recently encountered an issue with one of my React components where the "className" attribute was being converted to "classname" in the resulting HTML, instead of the expected "class" attribute. The component had a custom element definition as follows: ...

What is the best way to send the index value from a ngFor loop to the component?

I am facing an issue with my code where I have an ngFor loop. Within this loop, there is a div element and I need to pass the index value to the TypeScript file when this div is clicked. As I am new to Angular 2, any guidance on how to achieve this would ...

"Pairing AngularJS 2 with Vaadin for a winning combination

Good day, I'm currently following a tutorial but encountering some challenges with integrating Vaadin and Angularjs2 into my Joomla Backend project. The error message I am facing is as follows: polymer-micro.html:196 Uncaught TypeError: Cannot read ...

Cloud Formation from CDK doesn't pause for addDependency to finish

I'm currently in the process of building a CDK stack and I am fairly new to CDK. My goal is to create a Simple Email Service (SES) ConfigurationSet followed by an EmailIdentity. The issue I encountered is that the creation of the EmailIdentity fails d ...

`Managing select tag data in Angular reactive forms`

Having an issue with selecting the gender option from JSON formatted data received from the backend. The gender is displayed as a select tag on the frontend, but it does not pre-select the option that corresponds to the gender value in the JSON data. The b ...

When an input event is dispatched in a unit test, the value changes of a form are not activated

Currently, I am testing a scenario where I need to verify if a value changes on the form when input is typed in. This particular project utilizes Nrwl nx as well as jest for testing purposes. The component code snippet is as follows: export class InputNu ...

The Axios and TypeScript promise rejection error is displaying an unknown type- cannot identify

Currently, I am encountering an issue where I am unable to utilize a returned error from a promise rejection due to its lack of typability with Typescript. For instance, in the scenario where a signup request fails because the username is already taken, I ...

Declare the type of variable associated with the store configuration

After setting up a pinia store using the setup store syntax as described in the documentation at , I encountered an issue while working with typescript and setup stores instead of option stores for my project. The problem arises with type annotations for ...

Typescript fails to recognize a value assigned within an await statement

Looking at the code snippet below, we see that the variable x starts off undefined and can later be assigned a value of 1 within an `await` promise. Despite setting x to 1 inside the awaited promise, TypeScript still perceives it as undefined after the pr ...

What steps can I take to avoid cross-project contamination within an Angular workspace?

Imagine having a project structured like this: projects |-app1 |-app2 |-common node_modules pakcage.json tsconfig.json angular.json ... (other root files) Currently, in a file within app1, you can have an import statement like this: import { Repository } ...

The issue arises in ts-jest nestjs where there is an attempt to access properties of an undefined

Creating an application using NestJS and utilizing ts-jest for e2e testing. For the code repository, visit: https://github.com/redplane/jest-issue A controller is set up with the following structure: @Controller({ path: 'api/shape', scope: S ...

Utilize a personalized useFetch hook in React.js to transmit a POST request and obtain a response

I recently came across a great resource on this website that provided the logic for a useFetch hook. My goal is simple - I want to send a post request and then map the response into a specific type. While this seems like it should be straightforward, I&apo ...

Is it possible to use a single type predicate for multiple variables in order to achieve type inference?

Is there a way to optimize the repeated calls in this code snippet by applying a map to a type predicate so that TSC can still recognize A and B as iterables (which Sets are)? if(isSet(A) && isSet(B)) { ...