Waiting for variable to become false using Angular 7 Observable

The observable below highlights the authentication process:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CookieService } from 'ngx-cookie-service';
import { Observable } from 'rxjs';

@Injectable()
export class AuthService {
    readonly loginUrl = <login_url>;
    readonly authStatusUrl = <auth_status_url>;

constructor(private http: HttpClient, private cookieService: CookieService) {}

loggingIn = false;

login(username: string, password: string) {
    this.loggingIn = true;
    const creds = {
        username: username,
        password: password
    };
    this.http
    .post<any>(this.loginUrl, creds, {})
    .subscribe(
        data => this.onLoginSuccess(data),
        error => this.onLoginFail(error));
}

handleAuth(): Observable<any> {

    const token = this.cookieService.get('token');
    const refresh = this.cookieService.get('refresh');

    // should wait for loggingIn to be false
    return this.http
        .post<any>(this.authStatusUrl, { }, {
            headers: {
                token: token,
                refresh: refresh
            }
        });
}

public onLoginSuccess(data) {
    this.loggingIn = false;
    this.cookieService.set('token', data.access_token);
    this.cookieService.set('refresh', data.refresh_token);
}

onLoginFail(err) {
    console.log('Failed to login');
    this.loggingIn = false;
}

}

The function should only run if a local variable is set to false.

I have come across suggestions of using Promises and async function calls with the await operator to achieve this, however, I am struggling to find a solution that effectively polls for the variable value rather than just waiting for a specific amount of time before resolving.

The primary goal is to invoke handleAuth while ensuring that no ongoing login operation is in progress, by monitoring the local variable or another triggering event.

Answer №1

If you need to update the value of a local variable, you can do so by using a setter method like this:

private _localVariable;


setLocalValue(newValue) {
  this._localVariable = newValue;
  if(this._localVariable) {
   //perform your desired action here.
  }
}

Answer №2

One solution is to transform the variable loggingIn into a Subject, insert the "done" event into it, and then apply the flatMap function by combining loggingIn with the http.post.

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

Create type definitions for React components in JavaScript that utilize the `prop-types` library

Exploring a component structure, we have: import PropTypes from 'prop-types'; import React from 'react'; export default class Tooltip extends React.Component { static propTypes = { /** * Some children components */ ...

The Jasmine test is having trouble locating the imported variable

In my Angular project, I have a class set up as follows: import { USERS } from "./data/users"; // imports an Array of Objects export class User { constructor(name: string) { const user = USERS.find(e => e.name === name); } ... } Every ...

Troubleshooting: Vee-validate useResetForm not functioning properly during submission in Vue 3 with Typescript

I've been struggling to reset form data after submission, and it seems like the useResetForm hook isn't working as expected. Code Section <script setup lang="ts"> import CircularProgress from "@/components/CircularProgress. ...

When the back button is pressed on android, the navbar does not immediately refresh the active class

When using a webapp on Chrome for Android, pressing the back button results in double active items in the navbar. Clicking outside of the navbar removes the old active item. I attempted to resolve the issue by adding [routerLinkActiveOptions]="{ exact: tr ...

Discovering alterations in a component's attribute -Ang8

In my component, there are buttons to set the properties as follows: dataType:String = null fechaI : Date = null fechaF :Date = null checkedList =[] I need to trigger an HTTP request when all properties have values and redo the request if any of them ...

Formatting dates in Angular 2 and handling them in MongoDB with Express

I am currently working with Angular 2 and ExpressJS along with MongoDB. I have a date format that is being retrieved as 2016-06-02T14:20:27.062Z, but I need to display it in the format 06/02/2016 14:20:27 Express: In models/user.js: var userSchema = Sch ...

Enhance the visual appeal of your checkboxes in React Fluent UI by customizing the color of the checked mark and

I have a React application using Fluent UI. Currently, the <Checkbox/> component is displaying with its default colors and behavior like this: I want to customize the color of the checked mark and label (Green for checked mark and brown for label). ...

What is the best way to prevent double clicks when using an external onClick function and an internal Link simultaneously

Encountering an issue with nextjs 13, let me explain the situation: Within a card component, there is an external div containing an internal link to navigate to a single product page. Using onClick on the external div enables it to gain focus (necessary f ...

What is the best way to transform this date string into a valid Firestore timestamp?

Currently, I am facing an issue in my Angular application that is integrated with Firebase Firestore database. The problem lies in updating a date field from a Firestore timestamp field. To provide some context, I have set up an update form which triggers ...

Error: Trying to access the 'checked' property of an undefined variable

Currently, I am working on populating my panel with data from a web API (which is already functioning) while also allowing users to add new points to the list through the panel. This is my checkbox panel: <div class="generalCharacteristicsHover" (mo ...

Creating Angular unit test modules

When it comes to creating unit test cases for an Angular app, the application functionality is typically divided into modules based on the requirements. In order to avoid the need for repeated imports in component files, the necessary components, modules, ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

"Revolutionizing the way we navigate: Angular's innovative

Presently, my focus is on incorporating route transitions into my project. I've employed a component that appears on click and triggers the corresponding service function: routeTransition(destination) { if (this.router.url !== destination) { t ...

The HttpParams are reluctant to be established

Working with Angular 8, I am attempting to assign an HttpParam using the provided code snippet and observing the outcome on the final line. let newParams = new HttpParams(); newParams.set('ordering', 'name'); console.log('getting: ...

Issue with angular 8 radio button not being selected

Here is the HTML code I am working with: <div *ngFor="let option of systemEquipmentGroup"> <h5>{{option.optionGroupName}}</h5> <div> <label style="display: block;" * ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

Type arguments cannot be accepted in untyped function calls.ts(2347)

My user schema in typescript includes the following interface: interface IUser{ name: string; email: string; password: string; isAdmin: boolean; } Check out the user schema below: const UserSchema = new Schema<IUser>( { name: { type ...

Purge the inversify-js container and fetch fresh service instances

My frontend application in react-native utilizes inversify-js for service classes. I have implemented an IOC structure where services are shared as singleton instances, each with an init/destroy method to manage internal state. While the init/destroy mec ...

Utilizing mp3 files in Webpack 5 with Next.js

After hours of struggling with my current project using [email protected] and webpack v5, I found myself stuck on fixing mp3 loading. Despite trying various solutions from Stack Overflow and GitHub, none seemed to work for me. Type error: Cannot find ...

TypeORM: establishing many-to-one relationships between different types of entities

Trying to represent a complex relationship in TypeORM: [ItemContainer]-(0..1)---(0..n)-[ContainableItem]-(0..n)---(0..1)-[ItemLocation] In simpler terms: A ContainableItem can exist either within an ItemContainer or at an ItemLocation. Although it cannot ...