What is the best way to create a method that waits for a POST request to complete?

I have the following code snippet:

login() {
    const body = JSON.stringify({
      "usuario":"juanma",
      "password":"1234"});
    console.log(body);
    let tokencito:string = ''
    const params = new HttpParams();
    const headers = new HttpHeaders();
    this.http.post<AuthResponse>("http://localhost:8000/login", body, {'headers':headers,'params':params})
      .subscribe(data =>
        // @ts-ignore
     this.tokencito = data.token.token, localStorage.setItem('token', this.tokencito));
    console.log(localStorage.getItem('token'))
  }

I am using this code to retrieve a token from a user in PHP. However, it does not wait for the data to be retrieved. When I execute it for the first time, it returns 'data' as undefined. But when I run it a second time, it retrieves the token correctly.

An image has been included below for better clarification:

https://i.sstatic.net/RVsOW.png

Is there a way to make it wait for the post method to finish before proceeding?

Answer №1

Incorrect syntax alert! Use the following code snippet instead:

  login() {
    const body = JSON.stringify({
      username: 'johnsmith',
      password: 'secure123',
    });
    console.log(body);
    const params = new HttpParams();
    const headers = new HttpHeaders();
    this.http.post<any>('http://localhost:8000/login', body, { headers: headers, params: params }).subscribe((data) => {
      this.tokenValue = data.token.token;
      localStorage.setItem('token', this.tokenValue);
    });
  }

Avoid overriding TypeScript warnings. They're there to help you improve your code.

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

Angular observable goes unnoticed

I'm venturing into creating my own observable for the first time, and I'm running into issues. The data is visible in the console, but it doesn't show up when the component loads. Can anyone help me troubleshoot this problem? Here's a ...

In the realm of JavaScript and TypeScript, the task at hand is to locate '*' , '**' and '`' within a string and substitute them with <strong></strong> and <code></code>

As part of our string processing task, we are looking to apply formatting to text enclosed within '*' and '**' with <strong></strong>, and text surrounded by backticks with <code> </code>. I've implemented a ...

Having trouble determining the total amount in my online shopping cart

I am facing an issue with the shopping cart I created, which consists of two components (Productlist and Cart List). When I click on the 'add to cart' button in the Product List, it successfully moves into the service file and then to the Cart Li ...

What are the steps to prevent exceptions from being displayed when an Angular project times out?

Despite the absence of a debugger or breakpoints provided, the execution halts here whenever the Angular project is logged out due to timeout. https://i.sstatic.net/OFsvI.png ...

It is possible that the object may be null, as indicated by TS2531 error

I was interested in using QrReader to scan a file based on [https://github.com/Musawirkhann/react_qrcode_generation_scanner This code is written in react, but I wanted to use it with tsx. However, when attempting to implement it, I encountered an error: ...

typescriptIs it possible to disregard the static variable and ensure that it is correctly enforced

I have the following code snippet: export class X { static foo: { bar: number; }; } const bar = X.foo.bar Unfortunately, it appears that TypeScript doesn't properly detect if X.foo could potentially be undefined. Interestingly, TypeScript ...

How to implement a dynamic tag using TypeScript in React?

How can I implement dynamic tag typing in React using TypeScript? Take a look at the following code snippet: interface CompProps { tag: string; } const MyComponent: React.FunctionComponent<CompProps> = ({ tag = "div", children }) => { co ...

What is the best method for releasing an NX library along with all its bundled dependencies?

This problem is quite common in GitHub's NX repository, but I have not been able to find a solution there. Within my workspace, I have two buildable libraries: ui/avatar and ui/icon, as well as a publishable library named bar The goal is to utilize ...

TypeScript's Named Type Association

In my project, I have implemented a system that connects names to specific types through a Mapping Object Type called TMap The purpose of this system is to provide a handler function with information about one of the named types along with its correspondi ...

Leverage Angular to implement Bootstrap 5 tooltip on elements created dynamically

Our Angular-14 application uses Bootstrap-5 and I am currently attempting to add a tooltip to an element that is dynamically created after the page loads. The new element is based on an existing element, shown below: <span [ngbTooltip]="tipSEConte ...

Optimal strategies for managing subscriptions in Angular

I'm currently pondering about the concept of angular subscription and unsubscription. The amount of information available on this topic is overwhelming, making it hard for me to navigate through. When is the right time to unsubscribe from a subscript ...

Troubleshooting issue with problemMatcher in VSCode TypeScript compiler not functioning

I am looking for a problem matcher that can detect two types of issues: compilation problems related to TypeScript issues flagged by tslint This feature seems to be causing trouble in one of my projects, although it functions properly in others. Below i ...

utilizing tabview for component replacement

Having trouble changing components in Angular 7 with PrimeNG tabview tabs? Need some assistance? I have a setup with 3 components, and I want to switch between them when clicking on the panel inside the tabview. I've tried using onchange functions i ...

What is the correct way to forcefully override an existing type in TypeScript?

As I work with Formik, a React form library, I find myself creating custom fields and utilizing the generic Schema type provided by Formik. This type represents the values object, which holds all the values for each field in the form. One of the custom co ...

Creating a hierarchical visualization in Angular using a JSON object array

I'm currently working on creating a hierarchical view of users. My ultimate goal is to utilize this hierarchy view or something similar. The challenge lies in how the JSON objects used to construct the hierarchy are structured. Here's an example ...

What strategies can be used to manage Error return types in Typescript?

I have a situation where I need to handle either an object of type Person or an Error being returned by a function. My goal is to read the values of keys in the returned object only if it's not an Error. The code snippet below throws an error on the ...

What factors does mongo consider when serializing an object?

I recently started working with BigNumbers from the bignumber.js package As I delve into Mongo, I find myself pondering how Mongo manages to serialize objects correctly, such as the BigNumbers. In my case, I have encountered a puzzling situation where two ...

What is the best way to ensure that a class instance only receives the necessary properties?

In my code, I have a function that takes in an object called DataObject and uses certain properties from it to create instances of a class. To determine which data object items should be assigned to which class properties, I use mappings in the form of a ...

Am I effectively implementing async await in TypeScript?

I'm not quite sure if I'm using the async/await functionality correctly in my TypeScript and Protractor code. Looking at the code snippet below, the spec uses await to call the page object, which itself is an async/await function. The page object ...

What is the process for retrieving the information sent from the client application to the jsreport server?

I want to create a downloadable pdf report through my angular application using jsreport. The client app makes a POST request passing sample data to the report server in this manner. $http.post('http://localhost:5488/api/report', { ' ...