Patiently waiting for the component variable to be assigned through subscription

I am facing an issue with two calls in my component. The second call depends on the result from the first call. In the first call, I set the value for my component variable "locked". The second call should only be executed when the result is true, meaning locked = true. However, it seems to reach the code before the completion of the first call and setting the value. How can I delay the execution of my code until the call "getByUsernamer" is finished?

Below is the relevant code snippet:

export class LoginComponent implements OnInit {
  
  errorMessage: string = "";
  isLocked = false;
  username: string | null = "";

  constructor(
    private authService: AuthService,
    private cookieService: CookieService,
    private router: Router,
    private jwtTokenService: JwtTokenService,
    private userService: UserService) {
  }

  ngOnInit(): void {
  }

  test() {
    this.userService.getUserByUsername(this.username)?.subscribe({
      next: response => {
        let user: User = response;
        this.isLocked = user.locked
      }
    });

    if (!this.isLocked) {
      this.router.navigate(['/home']).finally(() => this.userService.setLastLogin(this.username).subscribe());
    } else {
      this.errorMessage = "The user is locked.";
    }
  }
}

Answer №1

To ensure that you have received the answer and the isLocked variable is set, you can check the status of the isLocked variable within the callback function of the initial request.

export class LoginComponent implements OnInit {
  
  errorMessage: string = "";
  isLocked = false;
  username: string | null = "";

  constructor(
    private authService: AuthService,
    private cookieService: CookieService,
    private router: Router,
    private jwtTokenService: JwtTokenService,
    private userService: UserService) {
  }

  ngOnInit(): void {
  }

  test() {
    this.userService.getUserByUsername(this.username)?.subscribe(
      {
        next: response => {
          let user: User = response;
          this.isLocked = user.locked;

          // The check for isLocked status has been moved here to ensure it only runs after receiving the initial response
          if (!this.isLocked) {
            this.router.navigate(['/home']).finally(() => this.userService.setLastLogin(this.username).subscribe());
          } else {
            this.errorMessage = "The user is locked."
          }
        }
      }
    );
  }
}

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

Discover the process of accessing and setting values in Angular 8 to easily retrieve and manipulate data from any page!

Greetings! I am currently utilizing Angular 8 and I have a query regarding how to access the set value in any given page. Here is a snippet of my code: class.ts export class testClass { get test():string{ return this.sexe; } ...

Tips for incorporating Angular-specific code into Monaco Editor

I am currently developing a browser-based IDE using the Monaco editor. I'm allowing users to input Angular-specific code into the editor, like this: import { Component } from '@angular/core'; @Component({ selector: 'app-root', ...

Angular2 material dropdown menu

Currently, I am studying angular2 with its material design. One of the modules I am using is md-select for material and here is a snippet of my code: <md-select> <md-option value="1">1</md-option> <md-option value="2">2< ...

I'm currently working on developing a chat system, but I'm facing an issue where I am unable to send multiple messages consecutively. It seems like there is a problem with the form

My chat application is not allowing me to post multiple messages. Here is the code snippet responsible for sending messages: window.typing = false; var posted = 0; var canPost = 1; var donotrefresh = 0; document.forms['send'].addEventListener(& ...

How to implement Google Tag Manager using the next/script component in Next.js 11?

Version 11 of Next.js recently introduced a new approach with the Script component offering various strategies. To avoid duplicate tags, it is advised to implement Google TagManager using the afterInteractive strategy. In my experimentation: // _app.js ...

Guide on setting up an AWS code pipeline for Elastic Beanstalk deployment on ASP.NET Core 5.0 with Angular

I am facing a challenge with deploying my ASP.NET Core 5.0 application with Angular to the EBS Windows environment using AWS CodePipeline (CI / CD). Despite searching various internet resources for solutions, I have not been able to find much help. My att ...

The Javascript function I created references a variable that seems to be undefined in the code

Recently, I discovered a function that is triggered with an onclick event using "openNav()" from an HTML element. Below is the code snippet for this function: function openNav() { document.getElementById("nav-drawer").classList.add("nav-drawer-open"); ...

"Enhance user experience with Sweetalert 2's customizable sorting options for select inputs

Here is the code snippet that I am currently working with: this.getdata((params.....).then((data) => { var selectOptions = []; for (let i = 0; i < data.length; i++) { selectOptions[data[i].id_calc] = data[i].surname + " " + data[i ...

What are the steps to integrate a database into my Next.js application?

While I was experimenting with integrating postgresql into a nextjs project, I encountered an error 405 when trying to create an account. Below is the error message in the browser console: page.tsx:14 POST http://localhost:3000/api/auth/ ...

Angular2 API call error: The function .map defaultOptions.merge is not recognized

When attempting to call the API using the post method, I encountered the following error message: this._defaultOptions.merge is not a function ... I looked into some solutions and tried importing the following without success: import 'rxjs/add/ope ...

Evaluating Vue with AVA - The key is in the whitespace

Currently, I am engrossed in a Laracast Episode about Vue Testing with AVA. Everything has been going smoothly so far, but now I have encountered an intriguing bug. This is my notification.js: import test from 'ava'; import Notification from &ap ...

Tips for customizing the background-image path in CSS modules for Next.js v14 during development and production

I am currently utilizing Next.js version 14 to construct a webpage with the setup showcased in the image provided below. Within my index.module.scss file, I have integrated an image for the background design. The snippet of code is visible below: &am ...

`Typescript does not adhere to the specified type when used inside a for loop with a local

This code snippet declares a variable venuelist of type Venue array and initializes it as an empty array. The type Venue has a property named neighborhood. There is a for loop that iterates through the venuelist array and checks if the neighborhoods matc ...

The configuration file tsconfig.json did not contain any input

After downloading angular2-highcharts through npm for my application, I encountered an error in the tsconfig.json file of the package while using Visual Studio Code: file: 'file:///c%3A/pdws-view-v2/node_modules/angular2-highcharts/tsconfig.json&apos ...

Ways to utilize array reduce for organizing information

Can someone please guide me on how to use the reduce array method to sort entries by date in the following data: const entries = [ {date: 'lu'}, {date: 'lu'}, {date: 'ma'}, {date: 'ma'} ] I would like the ou ...

JavaScript has received an event on Server XHR

Situation: There is a scenario where the target API is external and cannot be altered. A JS client initiates sending data to the API upon clicking a button. The code snippet resembles something like this: $.ajax({ type: "POST", url: &quo ...

Prevent the <a> tag href attribute from functioning with jQuery

I came across this code snippet: <script type="text/javascript"> $(document).ready(function() { $("#thang").load("http://www.yahoo.com"); $(".SmoothLink").click( function() { $("#thang").fadeOut(); $("#thang").load( ...

Setting a default value for a textfield within Angular 4

Within my for loop, I am displaying the name and price of a selected product. Users can input a quantity, with the default being 1. How can I set the text field value to default to 1? I've attempted the following method but it doesn't seem to be ...

Error message in the browser console: Uncaught TypeError - The function allSections.addEventListener is not recognized

Whenever I inspect my browser console, I keep encountering this error: Uncaught TypeError: allSections.addEventListener is not a function at PageTransitions (app.js:16:17) at app.js:33:1 I find it strange because my VS Code editor does not display any err ...

Obtaining the IP address upon page load in Angular 4: A step-by-step guide

In the midst of my Angular4 project, I'm on a mission to fetch the system IP address upon page load and send it over to the API for storage in a MSSQL database. However, each time the page loads, two rows are inserted and the IP address is coming up a ...