Encountered a runtime error while processing 400 requests

Current Situation:

When authenticating the username and password in my Ionic 2 project using WebApi 2 token authentication, a token is returned if the credentials are correct. However, a 400 bad request error is returned if the credentials are incorrect. Upon receiving a response, I navigate to the next page, but if an error occurs, a custom error message is displayed.

Challenge:

One issue I am encountering is that when entering wrong credentials for the first time, only the custom error message is shown. But upon entering wrong credentials again, both the custom error message and the default Ionic error message are displayed.

Code Snippet:

login.ts

  doLogin() {
    if (this.Username !== undefined && this.Password !== undefined) {
      this.loading.present();
      this.authSrv.login(this.Username, this.Password).subscribe(data => {
        this.navCtrl.setRoot('HomePage');
        this.loading.dismiss();
      }, (err) => {
        this.errorMsg("Invalid Username/Password !" + err);
        this.loading.dismiss();
      });
    }
    else {
      this.errorMsg("Please enter Username/Password");
    }
  }

auth-service.ts

  login(username, password) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('username', username);
    urlSearchParams.append('password', password);
    urlSearchParams.append('grant_type', 'password');
    let body = urlSearchParams.toString()
    return this.http.post('http://' + this._api + '/postoken', body, { headers: headers }
    )
      .map(res => res.json())
      .map((res) => {
        if (res !== null) {
          localStorage.setItem('acess_token', res["access_token"]);
          localStorage.setItem('access_type', res["access_type"]);
          localStorage.setItem('expires_in', res["expires_in"]);
          this.loggedIn = true;
        }
        return res;
      });
  }

Screencast:

https://i.stack.imgur.com/GMFo4.gif

Error Screenshot:

https://i.stack.imgur.com/FZzg1.png

Any suggestions or advice would be greatly appreciated.

Answer №1

The LoadingController should only be invoked once.

Keep in mind that once the component is dismissed, it becomes unusable and a new one needs to be created.

The issue arises from not creating a new loading instance each time in the doLogin function.

doLogin() {
    if (this.Username !== undefined && this.Password !== undefined) {
      this.loading = this.loadingCtrl.create({ //create here
    content: 'Please wait...'
     });
      this.loading.present();
      this.authSrv.login(this.Username, this.Password).subscribe(data => {
        this.navCtrl.setRoot('HomePage');
        this.loading.dismiss();
      }, (err) => {
        this.errorMsg("Invalid Username/Password !" + err);
        this.loading.dismiss();
      });
    }
    else
      this.errorMsg("Please enter Username/Password");
  }

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

Holding an element in TypeScript Angular2 proved to be challenging due to an error encountered during the process

I attempted to access a div element in my HTML using ElementRef, document, and $('#ID') but unfortunately, it did not work. I tried implementing this in ngOnInit, ngAfterViewInit, and even in my constructor. Another method I tried was using @Vie ...

Jquery failing to trigger click() on a div with an id

Within my erb file, there exists a script that looks like the following: function checkJquery() { if(window.jQuery) { jQuery(document).ready(function() { alert('onready'); $('div#habla_topbar_div').click(function( ...

guide for dynamically loading angular modules

In my application, I have three modules: home, moduleA, and moduleB. Within my app component, I am making a call to an API called session which returns a value named mode. Depending on the mode being moduleA or moduleB, I need to lazy load the respective m ...

Can the base href in Angular be dynamically changed during runtime?

Within my single Angular application, I have set the base-href to /a/b/. This means that in my dist folder, there is an HTML file with <base href="/a/b/">. As a result, the browser recognizes that an image link like assets/images/logo.png can be foun ...

"Using JavaScript to trigger a button click event, and then

I have a question that I think may sound silly, but here it is. I have this code snippet: <script type="text/javascript"> $(document).ready(function(){ var email_value = prompt('Please enter your email address'); if(email_value !== null){ ...

Attempting to verify if a function is being invoked within a subscription, but finding that it never gets activated

I have a method that needs to be tested when called in an ngOnInit. Specifically, I want to ensure that when the ngOnInit is triggered, this.anotherService.methodToCall() is executed and verify what parameters it is called with. However, despite my effort ...

How can I manipulate image resolution and export images of varying sizes using Javascript?

I am new to using three js. I have successfully exported an image in png format using the WebGL renderer. However, when attempting to export the image in a different custom size resolution, the resolution does not change. How can I set the image resoluti ...

Could the issue be related to a bug in the combination of ng-repeat and ngInclude?

I've been experimenting with loading different templates in this manner: <div ng-class="{active:$first,in:$first,'tab-pane':true}" id="{{p.path}}_settings" ng-repeat="p in panes" ng-include="buildPath(p.path)"> </div> Here&apos ...

Utilize the _sortBy function from the lodash library to arrange an array based on a specific field

Looking at an array of objects similar to this: myArray = [ {AType: "aaa", Description: "De", …}, {AType: "bbb", Description: "Hi", …}, {AType: "ccc", Description: "Un", …}, {AType: "ddd", Description: ...

Live search bar feature with jQuery更新

I am currently working on creating a dynamic search bar that updates a list of items from the database based on the input value. Below is the code I have developed for this search bar: $(document).ready(function(){ $('#search').keyup(function ...

Improve the functionality of select[multiple] to allow for single-click modifications without the need for CMD/CTRL

I am attempting to modify the default functionality of a select element so that clicking once on its options changes their selected state. Essentially, I want to eliminate the confusing requirement of holding down shift/ctrl to select multiple options. I ...

Analyzing JSON information using an AJAX request from a local file

I have a PHP file on a web server that is executing queries to a MySQL database. Currently, I am testing a site on my local PC which utilizes a JS file with AJAX requests to retrieve JSON data from the mentioned PHP file. My question is whether it is fea ...

Having difficulty extracting image and product names from Amazon or Flipkart pages using Jsoup

I'm having trouble retrieving the main image and product name from Amazon or Flipkart using Jsoup. This is my Java/Jsoup code: // For amazon Connection connection = Jsoup.connect(url).timeout(5000).maxBodySize(1024*1024*10); Document doc = connectio ...

A guide on incorporating JavaScript variables within a GraphQL-tag mutation

I'm having trouble consistently using javascript variables inside graphql-tag queries and mutations when setting up an apollo server. Here's a specific issue I've encountered: gql` mutation SetDeviceFirebaseToken { SetDeviceFirebaseTok ...

The submission functionality of an Angular form can be triggered by a separate button

I am currently developing a Material App using Angular 12. The Form structure I have implemented is as follows: <form [formGroup]="form" class="normal-form" (ngSubmit)="onSubmit()"> <mat-grid-list cols="2" ...

Retrieve an array field across various documents and combine the elements to form a single object

Consider a scenario where there is a users collection. Each user document includes an array of posts called posts. The goal is to query this collection as follows: Retrieve 2 posts, starting at index Nstart and ending at index Nend, from each user in the ...

What is the proper method for invoking object (class) methods from a router?

My apologies for the vague title. Let me clarify what I am attempting to accomplish. In this scenario, there are two main components: A class called 'wallet.js' A router named 'index.js' which handles GET requests This is my objectiv ...

Steps for regularly executing 'npm run build' on the server

My website doesn't require frequent content updates, as users don't always need the latest information. As a result, most pages are generated server-side and served as static pages. There will be occasional database updates that need to be visib ...

Pass an image into an input field with the attribute type="filename" using JavaScript directly

My goal is to automate the process of uploading images by passing files directly to an input type="filename" control element using JavaScript. This way, I can avoid manually clicking [browse] and searching for a file in the BROWSE FOR FILES dialog. The re ...

Inconsistency found in Ajax DataTable data updates

Incorporating a DataTable ajax feature, I pass values to the controller. Here is a simplified version of the code: $(function() { $("#tableDiv").hide(); $("#submitDateFilters").on("click", function() { displayData(); $("#tableDiv").show(); ...