Waiting for the function to complete within an if statement

When attempting a test, I encountered an issue where the function does not wait for the database request to be made. It seems like the function initially returns undefined, and only after the request is completed it returns true or false causing the test to fail in the else condition.

The challenge lies within the RestService of Angular 4/5.

This function handles password validation in order to execute an update:


handler: data => {
  if (this.checkPassword(data.password)) {
    console.log("4--------");
    // logged in!
    let jsonCreate = {
        name: form.value.inputName,
        email: form.value.inputEmail,
        password: form.value.inputPassword,
        description: form.value.inputDescription,
        id: this.id
    };
    console.log('jsonCreate');
    console.log(jsonCreate);
    // add client to the database
    this.rest.put('usersClient/atualizacao', jsonCreate)
    .subscribe(userUpdated => {
        console.log(userUpdated);

    });
  } else {
    console.log("3--------");
    return false;
  }
}

Password check function:


public checkPassword(password){
  console.log("check");

let jsonPost = {};
jsonPost["email"] = this.user.email;
jsonPost["senha"] = password;
console.log(jsonPost);
this.rest.post('Login/clientAuth', jsonPost).subscribe(user => {
    console.log("11--------");
    if(this.isEmptyObject(user)==true){
        console.log("1--------");
      return false;
    }
    else{
        console.log("2--------");
        return true;

    }
});
}

Answer №1

When dealing with async actions, it is important to ensure that you return the observable generated by this.rest.post:

public checkPassword(password){
    ...
    return this.rest.post('Login/clientAuth', "").map(user => !this.isEmptyObject(user));
});

You can then subscribe to this observable within the context of data:

handler: data => {
    this.checkPassword(data.password).subscribe(isLoggedIn => {
        if (isLoggedIn) {
            let jsonCreate = {
                ...
            };

            this.rest.put('usersClient/atualizacao', jsonCreate).subscribe(userUpdated => {
                console.log(userUpdated);
            });
        } else {
            return false;
        }
    });
}

If you need to wait for the put action to complete outside of the data subscription, you should not directly subscribe to checkPassword. Instead, you can use flatMap as shown below:

handler: data => {
    this.checkPassword(data.password).flatMap(isLoggedIn => {
        if (isLoggedIn) {
            let jsonCreate = {
                ...
            };
            return this.rest.put('usersClient/atualizacao', jsonCreate).map(userUpdated => {
                console.log(userUpdated);
            });
        } else {
            return false;
        }
    });
}

Remember to also subscribe to data.

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

When updating data with Angular Reactive Forms, the default value of input appears as 'undefined' upon submission, even though it is bound to the value property rather than the placeholder

I have developed a versatile Angular component that I am using to create various forms for the purpose of easily modifying multiple data items. Within this component, I have incorporated 2 input fields which are tied to input properties while iterating ov ...

The npm script for running Protractor is encountering an error

Currently, I am facing an issue while trying to execute the conf.js file using an npm script. The conf.js file is generated within the JSFilesRepo/config folder after running the tsc command as I am utilizing TypeScript in conjunction with protractor-jasmi ...

Ways to specify the type signature for objects that incorporate a fresh method

My understanding is that in TypeScript, we use new() to structurally type a class constructor. But how do we type an object that includes a new method, for example: const k = { new() { return '123' } } ...

What are the best practices for utilizing generics effectively?

A series of interfaces has been defined: export interface FormData<T extends ControlData = any> { [type: string]: T; } export type FormResult<T extends FormData> = { [type in keyof T]: T[type]; }; export interface ControlData<T = any& ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...

React Typescript: exploring the power of dynamic types

Can dynamic typing be implemented? The JSON structure I am working with looks like this: { "fieldName": "Some text", "type": String, "inputType": "text" }, { "fieldName": "Some bool&q ...

The filtering process of an array using the filter() method is effective, however, it does not result in any visible changes on

script.js searchVideo = (keyword) => { this.input = keyword; if(this.items.length == 0){ this.filteredItems = []; } if(!this.input){ this.filteredItems = this.items; } const args = this ...

Retrieve the browser's language using a Service during initialization

Upon launching the application, I need to obtain the browser's language. To achieve this, I have created a service with the following code: import { Injectable } from '@angular/core'; import { TranslateService } from 'ng2-translate/ng2 ...

Encountering issues with installing angular/cli due to errors popping up

When attempting to install Angular in my terminal after completing the setup, I encountered the following error message: I have already installed: Node v6.10.3 npm ERR! Darwin 17.7.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-g ...

The React component was not able to receive any children as input

My Typescript-written React component is called GradientText.tsx: import React, { ReactNode } from "react" import { cn } from "@/lib/utils" const typeMap = { h1: "h1", h2: "h2", p: "p", } inte ...

The 'property find' is not present in the type Posts[]

Below is the interface I have designed: export interface Post { _id: string; admin: Admin; comments: PostComment[]; createdAt: Date; modified: boolean; text?: string; desc?: string; photoPath?: string; } However, when tryi ...

Interacting with ngModel in Angular 4 across different components

I need to apply a filter on my products based on the categoryId value stored in the category-component. The product list is displayed in the product-component, and I have a categoryFilter pipe that filters the products accordingly. However, this pipe requi ...

Can you explain the significance of "Result" in the .map operator of an Observable fetched from an http.get call in NativeScript with Angular?

I'm currently working on the Nativescript/Angular tutorial and I stumbled upon a particular piece of code that has left me puzzled. In chapter 4 (Nativescript modules), there is a section where they make an http.get request to fetch the Grocery List a ...

Using a class that extends the parent component to inject it

I have a variety of angular components, each containing a base list component. For example, the VegetablesComponent and FruitsComponent both have a BaseListComponent, along with other child components specific to vegetables or fruits. The BaseListComponen ...

How can I retrieve all the recipes associated with a specific user (id) using ASP.NET Core 3.1.1 MVC and Angular?

Currently delving into ASP.NET MVC, I am immersed in building a single-page application using ASP.NET Core 3.1.1 with APIs. Within my User.cs file, there exists a collection of the user's Recipes. Specifically, within my User class, there is a prope ...

Using the Angular async pipe with an object's property

Is there a way to use the async pipe without ngFor? I need to check a property of an object that is asynchronously loaded with an observable. This is what I have tried, but it's not working as expected: <ion-item *ngIf="user$.anonymouse | async"& ...

Ensure that the types of objects created by spreading are checked

When we spread two different types of objects to compose a new object in TypeScript, the type-checking is not automatically enforced. So how can we make sure that TypeScript performs the necessary checking? type TypeA = { id: number; } type TypeB = { ...

When set to synchronize:true in Typeorm, any changes to an entity will result in the many-to

As a newcomer to typeorm, I've encountered a peculiar issue with the synchronize: true setting in my ormconfig.js. Whenever I make changes to an entity with a Many-to-Many relationship, any data present in the join table prior to the entity modificati ...

Having trouble changing the value of a field within an object stored in an array in JavaScript/TypeScript?

I'm wrestling with what seems to be a straightforward issue, but for some reason I can't update the pos field value in the WorkSetTemplate object within an array. Here's the code snippet: export class WorkSetTemplate { static alignPosit ...

Can dynamic string types be declared in Typescript?

Let's consider the following scenario: export enum EEnv { devint, qa1 }; export type TEnv = keyof typeof EEnv; export const env:Record<TEnv, {something:number}> = { devint: { something: 1, }, qa1: { something: 1, }, } Now, I ai ...