简体   繁体   中英

Angular HTTP Post observable only works the first time it is called

On my front end web page there is a button to allow user submit data on click. User may submit the data multiple times through the same restful api. I use http.post method in angular to post the data but it only works for the first time user click submit.

 onClick() { //**code in here executed every time user click submit button**. this. subscription = this.http.post<any>("url",data,httpOptions).subscribe( //**code inside here only executed once. The next time user click submit button, it won't trigger execution**. ); } 

How can I make the post works every time user click submit button? Thanks in advance.

You'll need to supply the code for before 'this.subscription' and inside.. as we can only guess otherwise. If you can supply the HTML for the button also it may highlight the issue.

I have tried using the below and I have no issues:

 onClick() { //**code in here executed every time user click submit button**. this.subscription = this.http.post<any>("https://www.google.com", {}, {}).subscribe(result => { console.log(result); }); } 
 <button (click)="onClick()">Click me</button> 

Remember the Angular's design pattern: you have the components and services to manage your project. The service file has a injectable anotation.

Second: Is recommended have a method to call the requisitions. Maybe it could be the solution, because the angular lost the reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM