Only once I am subscribed to this observable from HttpClient.post. However, post request is getting executed twice, and thus adding same record twice. Note that all debug log statement shows, that only successful response from subscribe function is being printed (and executed) twice.
addTemplate(template) {
console.log('In addTemplate');
let authHeaders = new HttpHeaders();
authHeaders = authHeaders.set('Authorization', 'Bearer ' + localStorage.getItem('id_token'));
authHeaders = authHeaders.set('Content-Type', 'application/json');
const httpOptions = {
headers: authHeaders,
observe: 'body' as 'body',
responseType: 'json' as 'json'
};
console.log('^^^^^ addTemplate Service Header = ', httpOptions);
this.httpClient.post<any>(this.constants.URL + 'addTemplate', JSON.stringify(template),
{headers: authHeaders}).pipe().subscribe(
(response) => { console.log ('Added Template Successfully -->', response)},
(error) => { console.error('Got an Error while adding Template ->', error) }
);
}
Above function is called from here:
saveTemplate(){
const saveTemplate : ITemplate = Object.assign({}, this.templateForm.value);
console.log('Adding new Template with name -->', saveTemplate.name);
this.templateService.addTemplate(saveTemplate);
}
Here's the image of browser console:
Here's the image of browser's Network tab:
As you can see HttpClient.post call to addTemplate REST API is being called twice. Even if post call is subscribed only once and there is no other place it's being called from. Call log
console.log('^^^^^ addTemplate Service Header = ', httpOptions);
in addTemplate function in service is executed once but log (response) => { console.log ('Added Template Successfully -->', response)}, is executed twice.
I did try changing call to httpClient.post to use share() and publishLast().refCount() but nothing worked. Maybe I didn't do it right.
Using Angular 7.2 with rxjs 6.5.2 and rxjs/compat (Yes, I do have some legacy code that needs to upgrade to latest)
It was my mistake. The form was calling saveTemplate() as well as button... So it was being called twice.
<form [formGroup]="templateForm" autocomplete="off" novalidate (ngSubmit)="saveTemplate()">
Button:
<button mat-button mat-raised-button color="primary"
type="submit" (click)="saveTemplate()" [disabled]="templateForm.pristine">Save
Thanks @CaptainFindus, @Alexander Staroselsky and all for your help