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

Safari 11.1 and Angular 9 - config object missing a defined key-value

While using Safari, I have encountered a problem in the Primeng input text field. When I type into the text box, errors are logged into the console. handleKeypress — injected.entry.js:8231TypeError: undefined is not an object (evaluating 'settin ...

Unlimited requests sent to the server while subscribing to an observable on HTTP

I am currently enhancing an Angular2 website with a feature to display the name of the user who is logged in. While I have been successful in retrieving the necessary information from the back-end service, I am encountering an issue where requests are sen ...

What is the counterpart of $.isEmptyObject({}) in Typescript for checking if an object is

Is there a formal method for testing an Object (response from server) to see if it is empty? Currently, I am using jQuery to accomplish this. this.http.post(url, data, {headers: headers}).then( result => { if (!$.isEmptyObject(result ...

Enhancing TypeScript - Managing Variables within Namespace/Scope

Why is the console.log inside the function correctly logging the object, but after the function returns it logs undefined, failing to update the variable? In addition, when using this within testNameSpace, it returns window. Why is that? namespace testNa ...

The Vercel error indicates that the file or directory '/var/task/node_modules/shiki/themes/one-dark-pro.json' does not exist

import { serialize } from 'next-mdx-remote/serialize'; import readingTime from 'reading-time'; import remarkGfm from 'remark-gfm'; import rehypeSlug from 'rehype-slug'; import rehypeAutolinkHeadings from 'rehype ...

JavaScript has a feature called "functions" which allow the declaration of named blocks of

Currently, I am developing an Electron app in typescript. In my main.ts file, I have instantiated a custom CommunicationProvider class object. What I want is for this class to declare multiple methods (specified in an interface that it implements) but have ...

Using the currency pipe with a dynamic variable in Angular 2

My application utilizes CurrencyPipe, The current implementation is functional, <div class="price">{{123 | currConvert | currency:'USD':true:'3.2-2'}}</div> Now, I need to dynamically pass the currency from a model varia ...

Tips for eliminating the draggable item's shadow in Angular

Is there a way to remove the shadow seen under the backdrop when dragging an item in the Bootstrap modal dialog? In the image provided, I am trying to drag the "Personal Details" button..https://i.stack.imgur.com/uSNWD.png ...

Learn how to customize the global style within a child component in Angular and restrict the changes to only affect that specific component

I have applied some custom css styling in my global style.css file (src/style.css) for my Angular project. However, I encountered a problem when trying to override this styling in a specific component without affecting the rest of the project. Currently, I ...

Angular2 route-driven themes

Exploring Different Themes for Two Routes: /books and /paintings Seeking a Solution to Include Specific Stylesheet Links in index.html For the /books route, I wish to include: <link rel="stylesheet" href="/assets/css/reading-theme.css" /> And for ...

The displayed number of rows in the paginator selection is inaccurate

My table in Angular Material is displaying the 'Items per page' numbers under the table instead of under the select option element (orange marker). Can someone explain why this is happening? Here is my HTML template: <div class="containe ...

Exploring Attack on Titan alongside the concept of dynamic route templates in coding

I am currently working on creating a factory for an UrlMatcher. export const dummyMatcher: UrlMatcher = matchUrlFn(sitemap as any, 'dummy'); export const routes: Routes = [ { matcher: dummyMatcher, component: DummyComponent }, { path: &apos ...

Can the Okta clientId be securely shared in a public repository?

Setting up Okta authentication in an Angular application involves adding a configuration variable with the necessary settings for your OIDC app in the app.module.ts file. You can find more information here. const config = { issuer: 'https://dev-1 ...

Navigating user profile routes effectively involves understanding the structure of the application

I'm currently working on developing a user-list feature that will display all users, along with user-detail components for each individual user. My main goal is to restrict access so that only administrators can see the complete list of users, while ...

The data type 'string | undefined' cannot be assigned to the data type 'string' when working with .env variables

Trying to integrate next-auth into my nextjs-13 application, I encountered an error when attempting to use .env variables in the [...nextauth]/route.ts: Type 'string | undefined' is not assignable to type 'string'. https://i.stack.im ...

Tips for implementing dynamic properties in TypeScript modeling

Is there a way to avoid using ts-ignore when using object properties referenced as strings in TypeScript? For example, if I have something like: const myList = ['aaa', 'bbb', 'ccc']; const appContext = {}; for (let i=0; i< ...

Unable to play audio src in Angular 2 due to http request issue

The data I gathered and included in the audio source is not playing. component.detail.ts export class DetailComponent implements OnInit { @Input() detailName: string; @Output("playnhac") play = new EventEmitter(); private mp3Link:string; ...

Creating dynamic HTML with Angular 2 using property binding

After retrieving an HTML string from the database, I came across html='<span>{{name}}</span>' where 'name' is a component property. I am looking to display this string in HTML while maintaining the name binding. I have expl ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

The specified 'DOCUMENT' export could not be located within the '@angular/platform-browser' module

Encountered an issue while attempting to update my IONIC app from version 3 to 4 Tried updating all plugins and modules to the latest versions available, but no success. ERROR in ./node_modules/ionic-angular/components/app/app.js 24:35-43 "export 'D ...