Search code examples
angularhttp-post

how to call http post in custom scenario like this in angular?


I have created custom post method with almost same signature with original one like this ,

postcall(url: string, body: any | null, options: {headers?: HttpHeaders | {
          [header: string]: string | string[];
      };
       params?: HttpParams | {
          [param: string]: string | string[];
      };
      reportProgress?: boolean;
      responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
      withCredentials?: boolean;
  } = {}): Observable<any> {

    return this.http.post<any>(url,body,options.Headers?Headers:responseType);


  }

I am unable to pass option as parameter with above post call.Please let me how I can pass the argument. it should pass the options as we receive in postcall()'s formal argument.

edit-1,

My call would be

this.http.postcall(this.resumeapiserver,body,{responseType: 'text'});

or

 httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      
    })
  }

this.http.postcall(this.apiServer + '/applicants/', JSON.stringify(applicant), this.httpOptions)

this both should work ..

I am unable to make this call with following error,

[1]: https://i.sstatic.net/Ke493.png

error I am getting if I pass option directly


Solution

  • Try something like that:

      post(applicant: any) {
        const options = {
          headers: new HttpHeaders({
            'Content-Type': 'application/json',
          }),
        };
        this.http.post(this.apiServer + '/applicants/', applicant, options);
      }
    

    Your postcall function has an error, probably should be changed this line as follow:

        return this.http.post<any>(url, body, options);
    
    

    In my opinion, is not make al lot of sense this postcall function because is a copy of the httpClient post function. So, maybe, is better use directly the post function as I showed to you in my first example code.