如何在此代码中等待响应。在这段代码中,我在 ws 中发布了产品。我的问题是当 ws 的响应被延迟时,可能会发生我多次按下按钮提交的情况。我不得不等待响应无法多次按下按钮。
public createproduct(newprod: Product): Observable<boolean> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = newprod.generateUrlencodedParameters(this.auth.getCurrentUser().token);
return this.http.post(Api.getUrl(Api.URLS.createproduct), body, {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 0) {
return true;
} else {
return true;
}
});
}
你能告诉我如何实现这个想法吗?
谢谢
这是一个异步调用。
所以你要做的是,你返回一个 Observable 对象,它会在未来改变并返回一些东西。
您想要做的是在第一次调用后禁用该功能,直到它响应某事。
所以,如果你的按钮是这样的,<button (click)=sendRequest() ...
那么你应该像这样实现它:
<button (click)=sendRequest(), [disabled]="areWeWaiting">CLICK ME</button>
areWeWaiting = false;
sendRequest(){
this.areWeWaiting = true;
this.someService.createProduct().subscribe(response =>{
this.areWeWaiting = false;
// process the call here
}, error =>{ this.areWeWaiting = false; //process error here}
);
}
另外,我建议您删除.map
原始服务调用中的部分 - 使用新的httpClient api在需要的地方处理请求
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句