我一直在寻找解决方案,但找不到解决方案,您能帮我吗?此http帖子请求被调用了2次。
如果我再增加2次,则调用OPTIONS会是4次。
public addEmployeeService(data){
const url = environment.serverUrl + 'enfila/api/organization/CompanyStation/services';
return this.httpClient.post(
url,
data
);
}
这是我要订阅的课程:
addEmployeeService(service, i) {
this.personalCareConfigurationService
.addEmployeeService(service)
.subscribe((response) => {
if(response["Result"]) {
console.log('this is called twice.');
this.companyServices[i].checked = true;
this.toastrService.success("Servicio agregado con éxito.");
}
}, (error)=> {
this.toastrService.error("Error al agregar servicio.");
console.log('ERROR ', error);
});
}
我正在调用方法的HTML:
<form action="empleados_submit" method="get" accept-charset="utf-8" *ngIf="selectedEmployee.Status != 'P'">
<div class="form-check check-rounded" *ngFor="let servicio of companyServices; let i = index;">
<a href="#" (click)="addEmployeeService(servicio, i);">
<label class="form-check-label">
<span class="input">
<input class="form-check-input" type="checkbox" value="" [checked]="servicio.checked">
<i></i>
</span>
<i class="icon-cart"></i>
<span class="txt">
{{servicio.Name}}
</span>
</label>
</a>
</div>
答案 0 :(得分:0)
有一些解决方案可以为您服务,通常会发生这种情况,因为可观察项被触发了两次。调试以确定该函数是被调用两次还是被观察到的函数被调用两次,例如在功能的开头添加console.log。
1)在订阅之前添加.take(1)
,以限制运行订阅回调的次数。
2)回调/可观察方法有时很难(至少对我来说)。尝试使用async/await
重写代码,看看是否有帮助,例如
3)这两个方法(都名为addEmployeeService
都在同一个类中吗?DOM是否会调用错误的方法?
async addEmployeeService(service, i) {
try {
result = await this.personalCareConfigurationService.addEmployeeService(service).take(1).toPromise()
// Whatever you want to do here
} catch (err) {
// Error handling
}
}