Title: Why web api methods are called multiple times
Tags: .net;angular;asp.net-web-api;visual-studio-2017
Question: I am calling a web api method as shown below from angular,But web api methods are executed two times.Any idea why it is happening here. I have  put a console log in origin ,angular code and confirmed that it is called one time from angular.BUt strange web api methods are executed two times, something like running on thread.
Angular code
public Createsamples(): Observable<any&gt; {
var url = this.baseApiUrl + 'Test/Createsamples';
return this.httpService.post(url, JSON.stringify(obj), { headers: reqHeader, withCredentials: true });
Web api code
[System.Web.Http.RoutePrefix(&quot;api/Test&quot;)]
[EnableCors(origins: &quot;*&quot;, headers: &quot;*&quot;, methods: &quot;*&quot;)]
public class TestApiController
[Route(&quot;Createsamples&quot;)]
[System.Web.Http.HttpPost]
public IHttpActionResult Createsamples()
{
TestBO Bo = new TestBO ();
var result = Bo.Createsamples(obj);
return Ok(result);
}
Comment: @enno.void but console.log('called Getfiles'); i can see one time in browser

Comment: @DavidG no change

Comment: @ enno.void i edited with calling side code

Comment: browser network tab i can see 4 times calls, like one for 2 POST + Preflight and 2 fro OPTIONS

Comment: Button click event from another page will trigger one dialogue 'MatDialogRef' and that dialogue will call this function

Comment: where do you trigger your angular code? in which page event? ngOnInit ?

Comment: Show the part where `Getfiles` is called. Everytime you subscribe to Getfiles() a new Http-Request is fired

Comment: sure, you can do this: const a = Getfiles(); a.subscribe(); a.subscribe(); This show your console.log once, but http call is fired twice

Here is the accepted answer: You might be dealing with an RxJS side-effect.
Observables are cold and won't do any computation unless there are any subscriptions done to it.
Once you call subscribe or use the observable | async then the computations and Side-Effects kick in (in your case a network request).
In order to avoid side-effects you need to make the Observable shared by using the shareReplay(1) operator and re-use the Observable on your template:
// your component code
ngOnInit() {
this.dataSource$ = this.service.apiCall().pipe(
shareReplay(1)
<!-- On your HTML template --&gt;
<div *ngIf=&quot;dataSource$ | async as data&quot;&gt;{{data |json }}</div&gt;
<div *ngIf=&quot;dataSource$ | async as data&quot;&gt;{{data |json }}</div&gt;
Even though there are technically two subscriptions in this snippet, since we made the Observable shared you should only see 1 network request, and the result of it should be re-used.
If you perform this.service.apiCall() many times, then every time you're creating a new Observable that is not related what-so-ever with the others and there's no way the Observable is going to be shared
You can read more about sharing Observables and avoiding side-effects here
Comment for this answer: ,sorry for a late replay, it seems it is working, you are a champion.I was googling many places and could not see it..
Comment for this answer: Glad I was helpful! May I get an accept? <3

Here is another answer: I had a situation where I had a dropdown in the UI of my angular app that called a function on the component every time I change the dropdown. The function I called subscribed to an observable that got application state. Inside the .subscribe, I had an if statement that called 1 of 4 functions that made api calls, each of which that had their own .subscribe. Each dropdown selection created another subscription, and if I changed the dropdown 3 time, and made a subsequent call to one of those 4 endpoints, it would call it 3 times. 4 changes, 4 time and so on.
My issue was that I didn't unsubscribe to the outer subscription that got the application state that was attached to the function of the dropdown that called one of the 4 endpoint in the if. Any other endpoint I called executed once, but it always executed the last called of those 4 endpoints the number of times of subscriptions that were open.
So unsubscribing from that outer subscription solved my issue. Hope this helps someone.
Comment for this answer: As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 8, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:06/17/21', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<.net><angular><asp.net-web-api><visual-studio-2017>', 'Title': 'Why web api methods are called multiple times', 'ViewCount': 1843, 'id': 68016361, 'user_AboutMe': '', 'user_AccountId': 27184.0, 'user_DisplayName': 'peter', 'user_Reputation': 7788.0, 'user_Views': 1579.0, 'user_id': 71470.0}}