Angular调用C# API获取JSON后读取Sector字段显示undefined问题
问题:Angular读取API返回的Sector字段显示undefined
我从C# API获取到了正确的JSON响应,但在Angular中尝试读取其中的Sector元素时,控制台输出显示该值为undefined。相关代码及响应内容如下:
1. Angular服务代码
PostFileImport(uploadBy:string, periodId: number ,fileToUpload: File): Observable<any> { const endpoint = constants.BaseUrl_UAT + 'api/Vote/' + 'VotingRoster' //?periodId='+periodId +'&uploadBy='+uploadBy let formData = new FormData(); formData.append('fileKey', fileToUpload, fileToUpload.name); let params = new HttpParams().set("periodId",periodId.toString()).set("uploadBy",uploadBy) const options = { params: params, reportProgress: true, responseType: 'arraybuffer' as 'json' }; const req = new HttpRequest('POST', endpoint, formData, options); return this.http.request(req); //return this.http.post(endpoint, formData, options); }
2. Angular调用API的TS代码片段
this.UploadService.PostFileImport('sss', this.PeriodId, this.uploadFile) .subscribe((res:any) => { this.Sectortest = res.Sector; this.data = res; console.log("Sector:") console.log(this.Sectortest) console.log("all") console.log(this.data) }, error => { console.error(error) } ) console.log("fisnihed calling API..") }
3. C# API控制器代码
[HttpPost] public async Task<IHttpActionResult> VotingRoster(string uploadBy, int periodId) { //ActionResponse aRes = new ActionResponse(); try { var dal = new IIVoteCombinationsDAL(); var file = HttpContext.Current.Request.Files.Get(0); if (file == null) { throw new InvalidOperationException("Upload file is required"); } var result = new RosterLoad(); result = dal.UploadRosterValidationFileAsync( new IIVoteCombinationsDAL.UploadRosterValidationFileParams { FileStream = file.InputStream, UploadBy = uploadBy, PeriodId = periodId } ); return Ok(result); //return Task.FromResult<IHttpActionResult>(Ok(result)); } catch (Exception ex) { return InternalServerError(ex); }; }
4. API返回的JSON响应内容
{ "SOEID": [ { "InvalidSOEID": "7060" } ], "Sector": [ { "Sector": "Banks", "Status": "Existing" }, { "Sector": "Transportation", "Status": "Existing" } ], "Industry": [ { "Industry": "ccc", "Status": "New" } ] }
问题现象
控制台日志中,this.Sectortest输出为undefined,但完整的this.data能看到包含Sector字段的JSON结构。
问题原因及解决方法
核心问题在于Angular请求的responseType配置错误,以及http.request的响应处理逻辑:
- responseType设置错误
你将responseType指定为'arraybuffer' as 'json',这会导致API返回的JSON被解析为ArrayBuffer二进制数据,而非可直接访问属性的JavaScript对象,因此res.Sector会返回undefined。
方案一:修改responseType为json(推荐)
如果API仅返回JSON数据,直接移除或修改responseType配置:
const options = { params: params, reportProgress: true, // 移除responseType,默认即为'json' // responseType: 'json' };
同时,http.request返回的是Observable<HttpEvent<any>>,需要判断事件类型为HttpResponse后再访问body:
this.UploadService.PostFileImport('sss', this.PeriodId, this.uploadFile) .subscribe((res:any) => { if (res instanceof HttpResponse) { this.Sectortest = res.body.Sector; this.data = res.body; console.log("Sector:", this.Sectortest); console.log("all:", this.data); } }, error => { console.error(error) })
方案二:手动转换ArrayBuffer为JSON对象
如果必须保留responseType: 'arraybuffer'(比如API可能返回二进制数据),则需要手动将ArrayBuffer转换为JSON:
this.UploadService.PostFileImport('sss', this.PeriodId, this.uploadFile) .subscribe((res:any) => { if (res instanceof HttpResponse) { const jsonString = new TextDecoder().decode(res.body); const responseData = JSON.parse(jsonString); this.Sectortest = responseData.Sector; this.data = responseData; console.log("Sector:", this.Sectortest); console.log("all:", this.data); } }, error => { console.error(error) })
内容的提问来源于stack exchange,提问作者ella
相关产品推荐
相关产品推荐

