Angular HTTP POST请求中.map方法失效问题求助
修复方案
情况1:使用Angular HttpClient(Angular 4.3+ 推荐)
HttpClient 默认会自动解析响应为 JSON,不需要手动调用 res.json(),原来的 .map() 完全多余,反而会因为响应对象没有 json() 方法报错。同时可以简化Promise转换:
import { HttpClient, HttpHeaders } from '@angular/common/http'; // 构造函数注入HttpClient constructor(private http: HttpClient) {} public postForObject(endpoint: any, data: any) { const url = this.createBasicUrl(endpoint); const _data = this.arrangeData(data); const token = `Bearer ${RestProvider.BEARER_TOKEN}`; const headers = new HttpHeaders().set('Authorization', token); return this.http.post(url, _data, { headers }).toPromise(); }
情况2:使用旧版Http模块(Angular 4.3之前)
如果仍在使用旧的 Http 模块,需要确保正确导入RxJS的map操作符,并且可以优化Promise转换:
import { Http, Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; // 构造函数注入Http constructor(private http: Http) {} public postForObject(endpoint: any, data: any) { const url = this.createBasicUrl(endpoint); const _data = this.arrangeData(data); const token = `Bearer ${RestProvider.BEARER_TOKEN}`; const headers = new Headers(); headers.append('Authorization', token); return this.http.post(url, _data, { headers }) .map(res => res.json()) .toPromise(); }
关键问题说明
- HttpClient vs Http:现代Angular推荐用
HttpClient,它自动处理JSON解析,无需手动调用res.json(),这是你原来.map()报错的核心原因——响应已经是解析后的对象,没有json()方法。 - RxJS操作符导入:如果用旧版Http,RxJS 5.5之前需要单独导入
map操作符;RxJS 5.5+推荐用pipeable操作符:import { map } from 'rxjs/operators'; // 使用时 this.http.post(...) .pipe(map(res => res.json())) .toPromise(); - Promise转换优化:无需手动创建
new Promise,直接用RxJS的toPromise()方法更简洁可靠。
内容的提问来源于stack exchange,提问作者orcunkiris
相关产品推荐
相关产品推荐

