首页 > 解决方案 > 在 android studio 的 ionic 应用程序中获取 [object Promise] 作为 xml 响应

问题描述

我正在使用 angular 和 cordova 构建一个离子应用程序,目前在带有模拟器的 android studio 中运行它。

我调用了一个端点,应该得到一个xml 响应,但是我得到的只是 [object Promise] 作为响应。我使用离子原生 http 包,因为 HttpClient 角度方式由于 CORS 错误而不起作用。

代码如下所示:

import { Component } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';
import { Platform } from '@ionic/angular'; 
import { from } from 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(platform: Platform, private http: HTTP) {
    console.log("in http constructor");

    platform.ready().then((source) => {
      console.log("platform source: " + source);
      
      let headers = { "Accept": "text/xml" };
      this.getMethodWithNativeHttp("https://......", {headers, responseType: 'text' }, {}); 
    });
  }
  
  xmlStringToJson(xml: string) {
    const xml2js = require('xml2js');
    
    xml2js.parseString(xml, { mergeAttrs: true }, (err, result) => {
      if(err) {
        throw err;
      }
  
      const json = JSON.stringify(result, null, 4);
      console.log("JSON: " + json);
    });
  }
  

  getMethodWithNativeHttp(url: string, params?: any, options: any = {}) {
    this.http.setDataSerializer("utf8");
    let responseData = this.http.get(url, params, {})
        .then(resp => {
          this.xmlStringToJson(resp.data);
        });

    console.log("response data: " + from(responseData));
  }
}

android studio中的日志:

[INFO:CONSOLE(67678)] "Angular is running in development mode. Call enableProdMode() to enable production mode.", source: http://localhost:8100/vendor.js (67678)

[INFO:CONSOLE(9954)] "in http constructor", source: http://localhost:8100/src_app_home_home_module_ts.js (9954)

[INFO:CONSOLE(9128)] "[WDS] Live Reloading enabled.", source: http://localhost:8100/polyfills.js (9128)

[INFO:CONSOLE(89226)] "Ionic Native: deviceready event fired after 1491 ms", source: http://localhost:8100/vendor.js (89226)

[INFO:CONSOLE(9956)] "platform source: cordova", source: http://localhost:8100/src_app_home_home_module_ts.js (9956)

[INFO:CONSOLE(10121)] "respData: [object Promise]", source: http://localhost:8100/src_app_home_home_module_ts.js (10121)

当我在 Postman 中调用端点时,我得到了 xml 响应,如下所示:

<ns:loginResponse xmlns:ns="http://example.org">
  <ns:return>b8becff5adf94a5a9b47280f86fde61b</ns:return>
</ns:loginResponse>

知道如何获得正确的 xml 响应吗?

标签: angularxml-parsingionic-native

解决方案


推荐阅读