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

Ensure that the method is triggered

I have a builder class that implements an interface which it is expected to build. However, I would like to enforce one method of this class to be called at compile time, rather than runtime. The class is designed to be used as a chain of method calls and ...

What steps should I take to address and resolve this problem with my Angular $scope?

One of my partials utilizes a single controller named CaseNotesCtrl. However, I am encountering difficulties accessing $scope variables within this partial. Below is the code snippet: <div class="row" ng-show="$parent.loggedin" ng-controller="CaseNotes ...

Enhancing Styled Components in Material-UI with custom props and themes using Typescript

I am exploring the use of the Material UI styled components API to incorporate both a custom theme and some props into a specific custom element. Although I have managed to get either a custom theme or props working individually, I am struggling to make t ...

"Receiving an error message stating 'Was expecting 1 parameter, received 2' while trying to pass a useState function in TypeScript

I am encountering an issue with a component where I pass a useState setter to a utility function: export interface IData { editable: string[]; favourited: string[]; } const [data, setData] = useState<IData | undefined>(undefined) useEffect(() = ...

Breaking up and Substituting text within Angular 8's HTML structure

When I retrieve data from a REST api, I need to split the name parameter at '2330' and insert a line break. For example, if the name is: ABCD 2330 This is My Name, I want the output on my screen to appear as: ABCD 2330 This is My Name // this par ...

Event emission is not working in the Ionic directive

I've developed a custom Ionic 5 Directive for long press functionality. Take a look at the code snippet below: export class LongPressDirective implements AfterViewInit { private delay = 800; @Output() press = new EventEmitter(); action: any; ...

Issue with ngRepeat not functioning properly in ngMap

Although I have experience with similar tasks in the past, I've hit a roadblock while trying to accomplish something seemingly simple. This is my HTML code using ngMap: <html ng-app="myApp" ng-controller="mapCtrl as map"> .... <map center="5 ...

The Java value is not returned by the Observable<boolean> stream

I'm currently working on making a request to the backend for a boolean value using observables, but I'm struggling to figure out the best approach between .map and .subscribe. return this.http.put({url}, credentials, this.requestOptions) .ca ...

Angular 2: Issue with Table not Being Updated

https://i.stack.imgur.com/qLDUZ.png The UsersList component opens a new page upon clicking the table. https://i.stack.imgur.com/WwqIX.png After changing and saving user values, the updated value is not immediately reflected in the grid for the first tim ...

Utilizing React Typescript to dynamically render a duo of components

On a single page, I want to display two components simultaneously. There is a bottom navbar that, when clicked on, for example the profile icon, should render the profile page. However, I would like to change the color of the icon based on which component ...

Connect data from an HTML table depending on the chosen option in a dropdown menu using AngularJS, JQuery, JSON, and

Could you please correct my errors? It's not working as I have made some mistakes. I need an HTML table based on the selection. I have tried but cannot find a solution. I created a dropdown, and if I select any value from the dropdown and click a butt ...

Error message: When attempting to redirect to another route, there is a type error with 'this' as it is implicitly assigned the type 'any'

I'm facing an issue with a component I've built using hooks. I want it to redirect to a different route when a function is called and the server response is received. However, my TypeScript is throwing an error: Type error: 'this' impl ...

Utilizing Typescript with Angular 2 to efficiently convert JSON data into objects within HTTP requests

I am dealing with a file called location.json, which contains JSON data structured like this: { "locations": [ { "id": 1, "places": [ { "id": 1, "city": "A ...

When using Angular.js, I am encountering an unfamiliar service provider error while attempting to implement the animation module. Could this issue be related to how I am declaring modules without using "var ="?

The tutorial on Angular seems inconsistent when defining modules. On one hand, it shows the module defined like this: angular.module('appname', ['phonecatFilters','phonecatAnimations']). config(['$routeProvider', ...

Adding data to an AngularJS template

I am encountering an issue with a flag that I am toggling between true and false to alter the display of certain elements on my page. While it works outside of the template, integrating this value into the template itself has proven challenging. restrict: ...

What causes the Cassandra client driver to provide more detailed information compared to cqlsh?

I'm currently utilizing the datastax nodejs-driver to retrieve information about a keyspace from cassandra. const results = await client.execute( ` DESC KEYSPACE ${keyspace} ` ); The method client.execute provides a comprehensive object containin ...

What is the method in TypeScript for defining a property in an interface based on the keys of another property that has an unknown structure?

I recently utilized a module that had the capability to perform a certain task function print(obj, key) { console.log(obj[key]) } print({'test': 'content'}, '/* vs code will show code recommendation when typing */') I am e ...

Guide to sending a HTTP POST request with parameters in typescript

I need assistance sending a POST request using parameters in the following format: http://127.0.0.1:9000/api?command={"command":"value","params":{"key":"value","key":"value","key":"value","key":value,}} I attempted to do this but encountered an issue: l ...

Angular 11 - Error: The 'fetch' method could not be executed on the 'Window' object due to an illegal invocation

I have encountered an issue with a dependency in my current project. This particular dependency relies on isomorphic-unfetch for its functionality. Strangely, I am able to run isomorphic-unfetch without any problems within Angular 11. However, when I inclu ...

Tips for receiving string body parameters from Express routes in TypeScript instead of using the 'any' type?

I have a situation where I am passing a unique identifier called productId as a hidden input within a form: <form action="/cart" method="POST"> <button class="btn" type="submit">Add to Cart</button ...