POST (http service) angular 2

2019-09-12 00:43发布

问题:

I have this POST data in my angular 2 application:

postServices(property) {
    let body = JSON.stringify(property);
    let headers = new Headers({'Content-Type': 'application/json'});
    let options = new RequestOptions({ headers:headers });
    return this._http.post(this._url, body, options)
        .map(res => res.json());
}

And in my template i have this button:

 <button *ngIf="!!service_rec.servicecontrolled" 
 [style.background-color]="service_rec.controlled == 'true' ? 'green' :'orange'"
         class="btn btn-warning">
         {{ service_rec.servicecontrolled | json | toOnOff }}
 </button>

And how i can add event on (click)="" in my template with this http service?

回答1:

you can add a click handler on button through which you can call postService.

<button *ngIf="!!service_rec.servicecontrolled" (click)= "callingPostService()"
 [style.background-color]="service_rec.controlled == 'true' ? 'green' :'orange'"
         class="btn btn-warning">
         {{ service_rec.servicecontrolled | json | toOnOff }}
 </button>

in your component, something like this would do

callingPostService() {
    this._myService.postService('prop');
}


回答2:

It's quite unclear what problem you try to solve but I guess

(click)="myService.postService('someProp')"

is what you're looking for.



回答3:

You can handle the click event on your button with a call that executes the service method:

<button (click)= "executePostService()">(...)</button>

The executePostService method will call the service as described below. You need not forget to subscribe on the observable (observables are lazy) otherwise the HTTP request won't be executed:

constructor(private service:SomeHttpService) {
}

callingPostService() {
  this.service.postService('prop').subscribe();
}