HTTP

时间:2018-09-19 02:36:15

标签: angularjs typescript ionic-framework ionic3

我必须在代码中执行三个HTTP Post请求。前两个工作,我调试代码,它们返回正确的值,但是最后一个返回未定义。 我之所以提出这三项要求,是因为其中一项取决于另一项的响应。

登录按钮:

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.carregaEmpresas();
    })
    .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)
    });
});

承载公司的功能,由于未返回任何内容而在此处发生错误

carregaEmpresas(newpage: boolean = false) {
console.log(this.cpfLogin);
this.abreCarregando();

return new Promise((resolve, reject) => {
  this.EmpresaProvider.getEmpresas(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.lista_empresas = arr_emp;

      this.objEmp = [];
      for (let i = 0; i < this.lista_empresas.length; i++) {
        this.obj = {
          label:
            this.lista_empresas[i].Valor,
          type: 'radio',
          value: this.lista_empresas[i].Chave
        }
        this.objEmp.push(this.obj);
      }

      this.fechaCarregando();
      this.selectEmpresa();
    })
    .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)
    });
});

提供者角色:

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

      var arr = [];

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

      this.empresa_cod = arr[0].Chave.split("/", 1);
      var urlFilial = this.apiFilial + this.empresa_cod["0"];
      return this.http.get(urlFilial, 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];
    });
});

GetEmpresas代码:

getEmpresas(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_usuario.push({ "Cpf": Cpf });

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

            var arr = [];

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

            this.empresa_cod = arr[0].Chave.split("/", 1);
            var urlFilial = this.apiFilial + this.empresa_cod["0"];
            return this.http.get(urlFilial, 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.emp = 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);
    });
  }

1 个答案:

答案 0 :(得分:0)

这是草稿,因为我不确定我是否已经找到问题,但是我需要共享比注释中更多的代码。

我要尝试的第一件事是删除new Promise,因为您无论如何都没有解决或拒绝这些承诺。我也尝试删除window.setTimeout。此时,看来getEmpresas将返回对arr_emp的承诺,这是解析最终get响应的结果。如果执行此操作,那么then中的carregaEmpresas处理程序将收到arr_emp中生成的getEmpresas,因此您应该仅将参数命名为arr_emp并不要尝试再次解析它。此时的代码是:

class MyClass {
    // Dummy declarations to suppress TypeScript errors
    dados_login;
    cpfLogin;
    senhaLogin;
    http;
    url;
    token;
    error_login;
    presentAlert;
    abreCarregando;
    lista_empresas;
    objEmp;
    obj;
    fechaCarregando;
    selectEmpresa;

    EmpresaProvider: EmpresaProvider;

    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 });

          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.carregaEmpresas();
            })
            .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)
            });
    }

    carregaEmpresas(newpage: boolean = false) {
        console.log(this.cpfLogin);
        this.abreCarregando();

          this.EmpresaProvider.getEmpresas(this.token, this.cpfLogin)
            .then((/*response*/ arr_emp) => {
              /*
              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.lista_empresas = arr_emp;

              this.objEmp = [];
              for (let i = 0; i < this.lista_empresas.length; i++) {
                this.obj = {
                  label:
                    this.lista_empresas[i].Valor,
                  type: 'radio',
                  value: this.lista_empresas[i].Chave
                }
                this.objEmp.push(this.obj);
              }

              this.fechaCarregando();
              this.selectEmpresa();
            })
            .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)
            });
    }
}

class EmpresaProvider {
    // Dummy declarations to suppress TypeScript errors
    cpf_usuario;
    http;
    baseApiPath;
    empresa_cod;
    apiFilial;
    emp;

    getEmpresas(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_usuario.push({ "Cpf": Cpf });

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

                var arr = [];

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

                this.empresa_cod = arr[0].Chave.split("/", 1);
                var urlFilial = this.apiFilial + this.empresa_cod["0"];
                return this.http.get(urlFilial, 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.emp = 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];
              });

      }
}

请尝试使用此代码(当然已集成到您的原始程序中),并让我知道它是否有效,确切的错误是什么以及发生在哪一行。