Angular 2 synchronous method ensures that all operations are carried out in

There is a cell in the grid that displays the number of users for each company. This number is retrieved from a TypeScript method called getNumberOfUsers(), which makes a call to a Back-End web service to fetch the user count. However, all cells are showing 0, even though the getNumberOfUsers() method correctly logs the number of users in the console.

<tr>
   <td>
     {{ getNumberOfUsers() }}
   </td>
 </tr>

Component TypeScript file

getNumberOfUsers(): number {
  let NumUser = 0;
  this.callServices.getUserCount().subscribe((res: any) => {
    NumUser = JSON.parse(res._body).numberOfUser;
    Console.log(“NumUser=” + NumUser)
  },
    (err) => console.error(' getUserCount::err==' + err)
  );

  return NumUser;
}

CallService file

getUserCount(): Observable<any> {
  return this.http.post(this.apiUrl+'/getUserCount');
}

I am looking to convert this method into a synchronous one

Answer №1

When dealing with asynchronous methods, it's important to remember they won't work in a synchronous manner. For more information on how JavaScript handles AJAX responses in the background, check out this resource.

One solution could be utilizing the async pipe to display values that are populated asynchronously.

Make sure to adjust your factory method so it returns data in JSON format.

getUserCount ():Observable<any>
{
    return this.http.post(this.apiUrl+'/getUserCount').map(data => data.json())
}

//Modify getNumberOfUsers to return the getUserCount Observable 
getNumberOfUsers(): Observable<any>{
    this.callServices.getUserCount();
}

HTML

{{ (getNumberOfUsers() | async)?.numberOfUser}}

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 is the best way to showcase nested array JSON data in an HTML Table?

https://i.stack.imgur.com/OHL0A.png I attempted to access the following link http://jsfiddle.net/jlspake/v2L1ny8r/7/ but without any success. This is my TypeScript code: var viewModel = function(data){ var self = this; self.orders = ko.observableArr ...

Exploring the possibilities of combining AngularJS and Angular 2 routing with wildcard paths

I'm struggling with wildcard path routing in an app that's partially upgraded from AngularJS to ng2. Combining both types of routing involves the following: The initial step in creating a dual router setup is to include an Angular root comp ...

What is the best way to declare a class as global in TypeScript without repeating code?

Is it possible to define a global class in TypeScript without repeating code? The following approach doesn't seem to work: declare global { class A { hi() { return "hi" } } } export {} As a result, I had to resort to repeated code usage. Yo ...

Mapped Generics in Typescript allows you to manipulate and

Currently, I am attempting to utilize TypeScript generics in order to transform them into a new object structure. Essentially, my goal is to change: { key: { handler: () => string }, key2: { hander: () => number }, } to: ...

Is it possible for prettier to substitute var with let?

One of the tools I utilize to automatically format my Typescript code is prettier. My goal is to find out if there is a way to have prettier replace all instances of 'var' with 'let' during the formatting process. Below is the script I ...

Routes in Angular2 are given names to help identify them

Working with Angular2 using the AngularClass Webpack Starter has been a smooth experience so far. However, in the latest version of the starter pack, I encountered an issue when trying to name a new route "my.route" in the file ./src/app/app.routes.ts. ex ...

Mistakes following update to Angular 4 from Angular 2

After upgrading from Angular2 to Angular4, I encountered these errors in the CLI. While my app continues to function after the upgrade, I am curious about possible solutions to resolve these errors. Any suggestions? https://i.stack.imgur.com/CyYqw.png He ...

Is it possible to pass additional arguments to setState other than prevState and props?

I'm currently facing an issue with my component that involves calling a function called addOption, which is defined on its parent component. This function takes a parameter 'option' from a form field and concatenates it with an array of opti ...

Having trouble retrieving a controller property in my Angular 2 view

I'm dealing with an interface right now export interface IInterview { id: number; title: string; body: string; } When I use console.log(interview) in my controller, it displays: Object {title: "I SEE SOMETHING", id: 2, body: "THIS IS SO ...

Using Typescript to validate if an object contains a certain property as well as checking the value of

Attempting to define a type guard by checking for the presence of a specific property in an object and then verifying its value: const isJson = (myObject: unknown): myObject is Json => { return Boolean( myObject && typeof myObject === &apo ...

Tips for managing errors when using the mergeMap feature in Angular's Typeahead search

Currently working on implementing Typeahead search functionality using API data. When we input valid data, the autosuggestions work correctly. However, if we input invalid data, we receive an error message. The issue arises when trying to input valid dat ...

What is the correct way to retrieve a saved value from a user's browser using useCookies in React Typescript?

I have developed a simple program to learn how to save and load cookies in React while also modifying the loaded value. The main component is App.tsx, where users can click a button to increment a number: function App() { let [myNumber, setMyNumber] = us ...

Angular's NGX Spinner is efficiently blocking the entire page

I'm currently incorporating ngx-spinner into my Angular application, but I'm running into an issue where it's loading on the entire page instead of just a specific area. Below is the code that I'm using: <p> Hello name </p> ...

Creating a Carousel in Angular 2 Without Using External Libraries

I am attempting to create a custom carousel component for my Angular 2 project, however, I am unsure of how to proceed. Are you able to provide me with some examples without using any libraries such as ngx-bootstrap? ...

Creating a table with a horizontal layout using Angular Material's mat-table

I am currently utilizing angular material 8.2.3 for my website. However, I have encountered a seemingly simple issue that has me stuck. I am looking to display a table horizontally instead of vertically. In my table, I only have two columns. Below is the ...

Guide on importing an ES6 package into an Express Typescript Project that is being utilized by a Vite React package

My goal is to efficiently share zod models and JS functions between the backend (Express & TS) and frontend (Vite React) using a shared library stored on a gcloud npm repository. Although the shared library works flawlessly on the frontend, I continue to e ...

Using a unique component within PipeTransform in Angular 2: A guide

I am facing an issue where my custom component Status is not displaying correctly within my pipe transform. The browser only shows the value, without the < Status /> tags. It seems like the component is not being called at all. Can someone please ex ...

Creating columns on the fly within a row

I would like to create a layout where images are displayed in one row, but if the screen size changes, I don't want them to wrap and display below. Instead, I want to show a button that redirects to another page. I'm not sure how to achieve this. ...

How to Retrieve Rectangle Positions on a Canvas

I am facing a specific scenario: I have created a rectangle on the canvas. By using the mouse wheel, the user can zoom in and out based on the position of the mouse cursor. Below is the TypeScript code for zooming: this.context?.clearRect( 0, 0 ...

"Customizing the MsAdalAngular6Module setup on the fly - a step-by-step

In order to manage authentication in an Angular single page app, I am utilizing the microsoft adal wrapper available at https://github.com/manishrasrani/ms-adal-angular6. Following the documentation, I configure all necessary options during compile time u ...