0

Created an API with both observable and Promise in Angular like:

submitEnquiry(details){
      console.log(JSON.stringify(details));
       return new Promise((resolve, reject) => {
           let headers = new Headers();
           console.log("TOKEN"+this.token);
           headers.append('Content-Type', 'application/json');
           this.http.post(this.apiUrl+"api/enquiry/request?token="+this.token, JSON.stringify(details), {headers: headers})
             .subscribe(res => {
               let data = res.json();
               resolve(data);
             }, (err) => {
               reject(err);
             });

       });
     }

Second Method:

submitEnquiry(details):Observable<any> {
  const headers: HttpHeaders = new HttpHeaders();
  console.log(details);
  headers.append('Content-Type', 'application/json');
  headers.append('Authorization', 'Bearer '+this.authService.token);
  //return this.httpClient.get<Product[]>('http://13.126.17.194/colleges.php', {headers: headers.append('Authorization', this.authService.token)});
  return this.httpClient.post<any>(this.apiUrl+"api/enquiry/request?token="+this.authService.token, JSON.stringify(details),{headers:headers});
}

The issue I am facing is that. the first one works and JSON data is entered into the server while when I am using the later one it gives me invalid request error! What am I missing here? I know the best method is to use the observable..

  • HttpHeaders is **immutable**. Its methods **return** a new object. – JB Nizet Jan 30 '18 at 13:30
  • Possible duplicate of [Angular HttpClient append headers to HttpHeaders](https://stackoverflow.com/questions/47805542/angular-httpclient-append-headers-to-httpheaders) – JB Nizet Jan 30 '18 at 13:31
  • 1
    Also, setting the content type and stringifying to JSON is not necessary. HttpClient does that for you. – JB Nizet Jan 30 '18 at 13:32

0 Answers0