如何在Angular中发起SOAP调用?现有代码报错原因排查
问题核心原因
- 调用
HttpClient.post()时参数顺序错误:post(url, 请求体, 配置项)是固定参数顺序,你把配置项作为第二个参数(请求体)传入,Angular默认将配置对象序列化为JSON字符串发送,服务端期望接收以<开头的XML内容,却收到了以{开头的JSON,直接触发报错。 HttpHeaders、HttpParams是不可变类型,调用set()方法不会修改原有实例,必须接收返回的新实例才会生效,你原代码中设置的请求头、查询参数都没有实际生效。- SOAP请求要求请求体必须是完整的XML信封格式,你没有构造符合要求的SOAP XML请求体,参数不要直接用
HttpParams传递(仅当服务端明确要求参数放在查询串时才用,绝大多数SOAP服务要求参数嵌入XML信封内)。 - 你原代码的
subscribe只配置了成功回调,没有配置错误回调,所以请求报错后没有日志输出,看不到错误信息。
修正后的代码
soap.service.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class SoapService { constructor(private httpClient: HttpClient) { } getResponse() { // 1. 构造符合你服务要求的SOAP XML请求体,替换里面的命名空间、方法名、参数为你SoapUI中可成功调用的请求内容即可 const soapBody = ` <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="替换为你的服务命名空间"> <soapenv:Header/> <soapenv:Body> <ser:替换为你调用的方法名> <username>me</username> <acctId>1585</acctId> <domain>USR</domain> <active>true</active> </ser:替换为你调用的方法名> </soapenv:Body> </soapenv:Envelope> `.trim(); // 2. 正确构造HttpHeaders,不可变类型需要链式调用set并返回新实例 const myheaders = new HttpHeaders() .set('Content-Type', 'text/xml; charset=utf-8'); // 如果服务要求SOAPAction头,可从SoapUI的请求头里复制对应值,在这里加.set('SOAPAction', '你的SOAPAction值') // 3. 正确传参:第二个参数是XML请求体,第三个是配置项 return this.httpClient.post('替换为实际的SOAP服务地址', soapBody, { headers: myheaders, responseType: 'text' }); } }
app.component.ts
import { Component } from '@angular/core'; import { SoapService } from './soap.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { title = 'Test of SOAP calls' name = 'SOAP Prototype'; response: any; constructor(private soapService: SoapService) { this.soapService.getResponse().subscribe({ next: res => { console.log("返回数据: ", res); this.response = res; }, error: err => { console.error("调用出错: ", err); } }); } }
如果返回的XML需要转成JSON处理,可引入xml-js等第三方XML解析库做转换即可
内容的提问来源于stack exchange,提问作者humble
相关产品推荐
相关产品推荐

