Angular 4中HttpClient Delete带Body报错:RequestHeaders不存在于RequestOptionArgs
Fixing Angular 4 Delete Request Error: "requestheaders does not exist in type requestoptionargs"
Hey there, let's get this sorted out quickly! The issue you're hitting comes from mixing up the old Http module APIs with the newer HttpClient module in Angular 4. Here's what's wrong and how to fix it:
What's Causing the Error?
- Wrong Option Type: You're using
RequestOptions(from the old@angular/httpmodule) withHttpClient(from@angular/common/http). TheHttpClientexpects anHttpOptionsobject instead, which uses different property names. - Incorrect Property Name: You passed
reqHeadersto the options object, but the valid property name for headers inHttpOptionsis justheaders. - Unnecessary JSON Parsing: The
HttpClientautomatically parses JSON responses for you, so thatmap(rez => JSON.parse(rez))line is redundant.
Corrected Code
First, make sure you're importing the right classes from @angular/common/http:
import { HttpClient, HttpHeaders } from '@angular/common/http';
Then update your method like this:
myMethod(id: string, reason: string): Observable<any> { // Create HttpHeaders (instead of the old Headers class) const httpHeaders = new HttpHeaders({ 'Content-Type': 'application/json' }); // Use a plain object for the body - HttpClient will serialize it to JSON automatically const body = { reqId: id, reqReason: reason }; return this.httpClient.delete( `http://localhost:188/.../1677777555`, { headers: httpHeaders, body: body } // HttpOptions object with correct property names ); // You can keep your .catch(error => ...) block here for error handling }
Extra Notes
- If you were originally using the old
Httpmodule (notHttpClient), you could useRequestOptions, butHttpClientis the recommended approach in Angular 4+ for better performance and automatic JSON handling. - By passing a plain object as the body instead of a template string, you avoid potential syntax errors and make the code cleaner.
内容的提问来源于stack exchange,提问作者annepic
相关产品推荐
相关产品推荐

