这个问题可能由于忘记在 HttpClient.post() 函数上使用 {observe: 'response'} 参数而导致。 {observe: 'response'} 参数用于返回HttpResponse,否则HttpClient返回的是响应主体。 如果没有指定返回的类型为HttpResponse,则无法调用pipe() 和 subscribe()。
示例代码:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) {}
postExample(): Observable {
return this.http.post('API_URL', {data: 'example'}, {observe: 'response'})
.pipe(
map((response: any) => {
console.log(response);
})
);
}
}
在 post() 方法中使用 {observe: 'response'} 参数,然后在pipe()中使用map()等操作符就可以处理响应了。