1. "The power of three vows in the world

I encountered an issue while making three HTTP Post requests in my code. The first two requests are successful, and upon debugging the code, they return the correct values. However, the third request returns undefined. The reason behind making these three requests is that one depends on the response of the other.

login button:

goToMenu() {
this.dados_login = [];
this.dados_login.push({
  "CPF": this.cpfLogin,
  "Senha": this.senhaLogin
})
let headers = new Headers();
headers.append('Content-Type', 'application/json; charset=UTF-8');
let options = new RequestOptions({ headers: headers });

return new Promise((resolve, reject) => {
  this.http.post(this.url, JSON.stringify(this.dados_login["0"]), options)
    .toPromise()
    .then((response) => {
      var json_token = (response as any)._body;
      var parsed = JSON.parse(json_token);

      var arr = [];

      for (var x in parsed) {
        arr.push(parsed[x]);
      }

      this.token = arr[0];

      this.loadCompanies();
    })
    .catch((error) => {
      var json_error = (error as any)._body;
      var parsed = JSON.parse(json_error);

      var arr = [];

      for (var x in parsed) {
        arr.push(parsed[x]);
      }

      this.error_login = arr[0];

      this.presentAlert(this.error_login)
    });
});

function that loads companies, encountering an error due to receiving nothing

loadCompanies(newpage: boolean = false) {
console.log(this.cpfLogin);
this.showLoading();

return new Promise((resolve, reject) => {
  this.CompanyProvider.getCompanies(this.token, this.cpfLogin)
    .then((response) => {
      var json_emp = (response as any)._body;
      var parsed = JSON.parse(json_emp);

      var arr_emp = [];

      for (var x in parsed) {
        arr_emp.push(parsed[x]);
      }

      this.companies_list = arr_emp;

      this.companyObj = [];
      for (let i = 0; i < this.companies_list.length; i++) {
        this.obj = {
          label:
            this.companies_list[i].Value,
          type: 'radio',
          value: this.companies_list[i].Key
        }
        this.companyObj.push(this.obj);
      }

      this.hideLoading();
      this.selectCompany();
    })
    .catch((error) => {
      var json_error = (error as any)._body;
      var parsed = JSON.parse(json_error);

      var arr = [];

      for (var x in parsed) {
        arr.push(parsed[x]);
      }

      this.error_login = arr[0];

      this.presentAlert(this.error_login)
    });
});

provider role:

return new Promise((resolve, reject) => {
  this.http.post(this.baseApiPath, JSON.stringify(this.cpf_usuario["0"]), options)
    .toPromise()
    .then((response) => {
      var company = (response as any)._body;
      var parsed = JSON.parse(company);

      var arr = [];

      for (var x in parsed) {
        arr.push(parsed[x]);
      }

      this.company_code = arr[0].Key.split("/", 1);
      var urlBranch = this.apiBranch + this.company_code["0"];
      return this.http.get(urlBranch, options);
    })
    .catch((error) => {
      var json_error = (error as any)._body;
      var parsed = JSON.parse(json_error);

      var arr = [];

      for (var x in parsed) {
        arr.push(parsed[x]);
      }

      return arr[0];
    });
});

GetCompanies Code:

getCompanies(token: string, Cpf: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json; charset=UTF-8');
    headers.append('Authorization', 'bearer ' + token);
    let options = new RequestOptions({ headers: headers });
    this.cpf_user.push({ "Cpf": Cpf });

    return new Promise(resolve => {
      window.setTimeout(() => {
        this.http.post(this.baseApiPath, JSON.stringify(this.cpf_user["0"]), options)
          .toPromise()
          .then((response) => {
            var company = (response as any)._body;
            var parsed = JSON.parse(company);

            var arr = [];

            for (var x in parsed) {
              arr.push(parsed[x]);
            }

            this.company_code = arr[0].Key.split("/", 1);
            var urlBranch = this.apiBranch + this.company_code["0"];
            return this.http.get(urlBranch, options)
              .toPromise()
              .then((response) => {
                var json_emp = (response as any)._body;
                var parsed = JSON.parse(json_emp);

                var arr_emp = [];

                for (var x in parsed) {
                  arr_emp.push(parsed[x]);
                }

                this.comp = arr_emp;
                return arr_emp;
              })
          })
          .catch((error) => {
            var json_error = (error as any)._body;
            var parsed = JSON.parse(json_error);

            var arr = [];

            for (var x in parsed) {
              arr.push(parsed[x]);
            }

            return arr[0];
          });
      }, 2000);
    });
  }

Answer №1

I am currently in the process of troubleshooting an issue and need to share more code than can be accommodated in a standard comment.

One potential solution to consider is removing the new Promise component since the promises are not being resolved or rejected. Additionally, it might be worth trying to eliminate the window.setTimeout section. By doing this, the getEmpresas function should return a promise for the arr_emp derived from parsing the final response obtained through get. In that scenario, the then handler within carregaEmpresas will receive the generated arr_emp from getEmpresas, so there is no need to parse it again. The modified code snippet would look something like:

[Insert modified code here]

Feel free to implement this code into your existing program and provide feedback on whether it resolves the issue. If not, please specify the exact error message and location.

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

Making AngularJS work with angular-ui bootstrap and ensuring compatibility with IE8

Having trouble getting AngularJS code that utilizes angular-ui bootstrap to function properly in IE 8? Following the guidelines in the AngularJS developer guide on IE didn't seem to solve the issue for me. I inserted the code snippet below into my ind ...

Develop an rxjs pipeline that merges values according to their type prior to executing them in an async manner using concatMap

In my code, there's an eventStream that deals with different types of events and sends them to the server via HTTP. import { from, Observable } from 'rxjs'; import { concatMap } from 'rxjs/operators'; type Update = number[]; inte ...

TS2322 error: Attempting to assign type 'any' to type 'never' is invalid

Currently, I am utilizing "typescript"- "3.8.3", and "mongoose": "5.9.11". Previously, my code was functional with version "typescript": "3.4.x", and "mongoose": "4.x". Here is a snippet of my code: https://i.stack.imgur.com/j3Ko2.png The definition for ...

Monitoring a variable inside a service using AngularJS

I am currently in the process of developing a web application using AngularJS. My application consists of a primary view (Index), a child view (Dashboard), and a grandchild view (Raiding The Rails). http://localhost:4000/#/dashboard/raiding-the-rails/1 ...

Mastering the mapping function in ReactJs for a Map<string, boolean> data structure

Just a quick question, I seem to be stuck on this. Here is my Map: public checkboxOptions: Map<string, boolean>; In the render() function, I want to loop through it like this: renderCheckboxMenu(): any { let menu = <div className={`${style[ ...

Deleting files with a dedicated function (Dropzone.js)

I need to implement functionality that removes the uploaded file when a 'cancel' button is clicked. Here's how my HTML code looks: <div reqdropzone="reqDropzoneConfig"> <form id="requisitionupload" class="dropzone dz-clickable" ac ...

Error: The identifier HTMLVideoElement has not been declared

Encountering an issue while attempting to build my Angular 9 Universal project for SSR: /Users/my-project/dist/server.js:28676 Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__metadata"])("design:type", HTMLVideoElement) ReferenceError: HTMLVideoElem ...

Angular's ng-include functionality allows developers to dynamically load

As a beginner in angular.js, I've written my first 'hello world' script. I'm attempting to use ng-include to bring in a navbar from the local file /templates/nav.html. Despite following a tutorial closely, I'm struggling to underst ...

"Extracting information from a database in Angular Laravel to create a Chart.js display - a step-by-step

Currently, I am working on developing a dashboard application that includes various charts. My aim is to customize the data displayed in each user's chart based on information retrieved from a database. This is how my setup looks like: HTML <div ...

The compilation of the Angular application is successful, however, errors are arising stating that the property does not exist with the 'ng build --prod' command

When compiling the Angular app, it is successful but encountered errors in 'ng build --prod' ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent&apo ...

Using resolve to preload data in Angular's $routeProvider initialization process

I am working on an AngularJS application and need to fetch data from a REST API before the controller initializes. I am using the "resolve" in my routeProvider and have injected the necessary value into the controller to ensure that the data is available. ...

The TypeScript reflection system is unable to deduce the GraphQL type in this case. To resolve this issue, it is necessary to explicitly specify the type for the 'id' property of the 'Address'

import { ObjectType, ID, Int, Field } from 'type-graphql'; @ObjectType() export default class Address { @Field(type => ID) id: String; @Field() type: string; @Field() title: string; @Field() location: string; } More informa ...

Clean coding techniques for toggling the visibility of elements in AngularJS

Hey everyone, I'm struggling with a common issue in my Angular projects: app.controller('indexController', function ($scope) { scope.hideWinkelContainer = true; scope.hideWinkelPaneel = true; scope.headerCart = false; scope. ...

How to efficiently remove duplicate items from multiple select dropdowns in Angular using ng-repeat?

Need help with dynamically assigning objects to select boxes in AngularJS. I have a scenario where I add multiple select boxes to a form, but each box should only display items that haven't been selected in other boxes. How can I achieve this functio ...

Utilizing a shared directive across multiple pages while maintaining its state

In my AngularJS app with multiple pages configured using $routeProvider, I have created a reusable directive that contains buttons allowing for callbacks and inputs. However, the directive relies on a service to maintain its state when transitioning betwee ...

Ways to extract the final digit from a format such as an IP address in JavaScript

Is there a way to retrieve the last digits 192.168.1.180 For instance: From the IP address 192.168.1.180, I would like to extract 180. Thank you in advance ...

What causes a Module Error to occur in my AngularJS application when I attempt to include multiple routes?

When there is a single .when() route in my app.js, the testApp module loads successfully and the site functions as expected. However, if I add additional routes (such as about and contact) using .when(), the module fails to load. Here is the error message ...

Encountering a Loopback 401 error while attempting to make updates

I've been attempting to make updates to a loopback user model, but every time I try, I encounter a 401 unauthorized error, even though my user role is set to admin. Below is the structure of my user.model: { "name": "user", "plural": "users ...

Navigate back to the main page using a tab

Is there a way to navigate back to the rootPage that is defined in the appComponent when using tabs? I have found that the setRoot method does not function as I anticipated. When used on a Tab page, the navigation stack is not cleared. Instead of the navig ...

Dealing with Uncaught Promises in Angular 2 while injecting a service

I followed the instructions in the official tutorial to start a project, but I'm encountering an issue with injecting services into my Angular2 app. Everything was working fine until I added a service. Here are the files : app.component.ts import ...