Promise rejection: not as expected

I encountered an issue while using alert messages in my login menu:

Runtime Error Uncaught (in promise): false Stack Error: Uncaught (in promise): false

Here is the code snippet causing the problem:

  public login() {
    this.showLoading()
    this.auth.login(this.Login).subscribe(allowed => {
      if (allowed) {        
        //this.navCtrl.setRoot('Inicio');
        this.usuarioLogueado = this.auth.getUserInfo();
        if(this.usuarioLogueado.tipo == "Administrador"){
          this.navCtrl.setRoot(Administrador);
        }
        console.log("Welcome",this.usuarioLogueado.usuario,this.usuarioLogueado.tipo);
      } else {
        this.showError("Access denied");
      }
    },
      error => {
        this.showError(error);
      });
  }

  showLoading() {
    this.loading = this.loadingCtrl.create({
      content: 'Please wait...',
      dismissOnPageChange: true
    });
    this.loading.present().then(() => this.loading.dismiss());
  }

  showError(text) {
this.loading.dismiss().catch(() => console.log('ERROR: Loading control failed'));
    let alert = this.alertCtrl.create({
      title: 'Failure',
      subTitle: text,
      buttons: ['OK']
    });
    alert.present(prompt);
  }


}

Answer №1

It appears that the issue lies within the following line of code:

this.loading.present().then(() => this.loading.dismiss());

The proper way to handle a loader is to display it before initiating the HTTP request and then hide it once the request is completed. The correct approach would be as follows:

// Assuming you already have a property to hold the instance of the loader 
public loading: any;

public login() {
    this.showLoading().then(() => { // Display the loader before the request

        this.auth.login(this.Login).subscribe(allowed => { // Initiate the HTTP request

            this.loading.dismiss().then(() => { // Hide the loader once request is complete

                if (allowed) {

                    // this.navCtrl.setRoot('Inicio');
                    this.usuarioLogueado = this.auth.getUserInfo();

                    if (this.usuarioLogueado.tipo == "Administrador") {
                        this.navCtrl.setRoot(Administrador);
                    }

                    console.log("Welcome", this.usuarioLogueado.usuario, this.usuarioLogueado.tipo);

                } else {
                    this.showError("Access denied");
                }
            });
        }, error => {
            this.loading.dismiss().then(() => { // Hide the loading
                this.showError(error);
            });
        });
    });

}

showLoading(): Promise<any> { // Return the promise
    this.loading = this.loadingCtrl.create({
        content: 'Please wait...',
        dismissOnPageChange: true
    });
    return this.loading.present(); // Added the return keyword here
}

showError(text) {
    let alert = this.alertCtrl.create({
        title: 'Error',
        subTitle: text,
        buttons: ['OK']
    });
    alert.present(prompt);
}

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

Determine data type using the generic type of a related property in Typescript

I am seeking a method to specify the type of a property based on the generic type of another property within the same context. For instance, consider the following: type Person = { id: number; name: string; } type Select<Value=unknown> = (props ...

Exploring Next JS: Effectively altering SVG attributes and incorporating new elements

I have integrated SVGR to load an SVG as a component in my latest Next.js 13 application: import CvSvg from './../../public/image.svg' export default function Home() { return ( <div className="flex flex-col min-h-screen" ...

Redis Recursion: The callstack has reached its maximum size limit

Looking for some assistance with creating a game timer. I've decided to utilize Redis and Web Sockets in order to synchronize the timer across multiple devices. However, I'm running into an issue when trying to call my function recursively using ...

Create an array using modern ES6 imports syntax

I am currently in the process of transitioning Node javascript code to typescript, necessitating a shift from using require() to import. Below is the initial javascript: const stuff = [ require("./elsewhere/part1"), require("./elsew ...

Resolving issues with Typescript declarations for React Component

Currently utilizing React 16.4.1 and Typescript 2.9.2, I am attempting to use the reaptcha library from here. The library is imported like so: import * as Reaptcha from 'reaptcha'; Since there are no type definitions provided, building results ...

What is the best way to implement a generic parameter with constraints in an abstract method?

Take a look at this scenario: interface BaseArgs { service: string } abstract class BaseClass { constructor(name: string, args: BaseArgs) { this.setFields(args) } abstract setFields<T extends BaseArgs>(args: T): void } interface ChildA ...

Passing headers using a universal method in HTTP CRUD process

My service function is structured like this: Please note: I am required to work with cookies book(data: Spa): Observable<any> { return this.http.post(`${environment.apiURL}:${environment.port}/${environment.domain}/abc/my.json`, data, { ...

Tips for effectively passing an array to props in Vue when leveraging Typescript and the class component decorator

I'm currently struggling to understand the proper method of passing an array as a prop to a component in Vue, using Typescript and the class component library. Following the official template, I attempted the following approach: <script lang="ts"& ...

Error encountered when attempting to locate the file declaration for module 'jwt-decode'

Currently, I am utilizing the Visual Studio 2017 template for my Angular project and encountering an issue when attempting to import the 'jwt-decode' module after adding it to package.json. The error (mentioned in the title of my post) arises aft ...

The error message "Property 'value' is not present on type 'EventTarget & HTMLSelectElement'" indicates that the 'value' property is not recognized on the Event

Here is the code snippet that I am working with: interface IHandleSelection { (value: string): any | void; } interface IPipeChangeEventValueToFunction { (handler: IHandleSelection): (event: React.ChangeEvent<HTMLSelectElement>) => void; ...

The communication between Angular and Unity using SignalR for messaging is not functioning properly, as I am unable to

Trying to establish a connection between Angular and Unity has been challenging for me. I can't seem to get them to communicate with each other. My goal is to have Angular "announce" when someone enters a room, and have Unity "greet" the user enterin ...

Guide on utilizing the h function in Vue3 for seamless binding and passing of properties and events from parent to child components

Utilizing Vue3 and naive ui for front-end development has been a challenge for me as I primarily focus on back-end development and lack expertise in front-end technologies. To enhance user interaction, I incorporated naive ui’s BasicTable along with an ...

Using Angular Material to dynamically hide columns in a table that is being created on the fly

Is there a way to hide columns in my table based on the ID value sent to the page upon opening it? While researching, I found a method for tables with dynamically generated columns in this post: https://github.com/angular/components/issues/9940. However, t ...

Guide to Setting Up Infinite Scroll with Next JS SSG

I recently built a markdown blog using the Next Js documentation and incorporated Typescript. When trying to retrieve a list of blog posts, I utilized getStaticProps as recommended in the documentation. However, my attempts with certain npm packages were u ...

Advanced Typescript contains a parameter that specifies the type of callback function

Is it possible to create a function that is more typesafe than the current implementation? public addBusinessRule(targetProperty: string, dependentProperties: string[], callback: (dep0: any, dep1: any, ...)): void { // s ...

The intricate field name of a TypeScript class

I have a TypeScript class that looks like this - export class News { title: string; snapshot: string; headerImage: string; } In my Angular service, I have a method that retrieves a list of news in the following way - private searchNews(sor ...

Even though there is data stored in the array, the React Native array.length appears to be returning a value

I am struggling with what appears to be a simple issue, and it's frustrating that I've had to seek help for this. The problem lies in iterating through an array messages: Message[] = [...]. No matter what method of iteration I try, it doesn&apos ...

Tidying up following the execution of an asynchronous function in useEffect

Recently, I've been facing a challenge while migrating a React project to TypeScript. Specifically, I'm having trouble with typing out a particular function and its corresponding useEffect. My understanding is that the registerListener function s ...

"TypeScript function returning a boolean value upon completion of a resolved promise

When working on a promise that returns a boolean in TypeScript, I encountered an error message that says: A 'get' accessor must return a value. The code snippet causing the issue is as follows: get tokenValid(): boolean { // Check if curre ...

From the service to the component, navigating the array in Angular

I'm encountering difficulties with Angular Services and I can't seem to pinpoint the issue. Currently, I am working on a book application that utilizes Promises. To enhance performance, I am restructuring my code by implementing service injectio ...