我需要将httpclient用于foreach循环。有可能的?什么是正确的方法?这是我的代码:
this.attachToDelete.forEach(
element => {
this.documentService.DeleteAttachment(element, this.newDocumentId.toString());
console.log("upload delete from submit", element);
}
);
这是对应服务中的方法:
public DeleteAttachment(attachmentId: number, documentId: string) {
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
return this.http.post('http://localhost:8080/DocumentAPI/api/document/RemoveAttachment?docId=' + documentId + '&attachmentId='+attachmentId, attachmentId, { headers: headers }).subscribe(
data => {
if(data)
console.log("delete attach????", data);
else{
console.log('Error occured');
}
}
);
}
从你开始,我会详细说明:)
您似乎已成功创建HTTP调用,对此表示祝贺。
创建HTTP调用时,您将创建一个Observable
。 Observable就像承诺,但他们做得更多。
具有可观察性的东西是,你需要订阅它们来触发它们。
这可以通过使用subscribe
链接HTTP调用来完成:
this.documentService
.DeleteAttachment(element, this.newDocumentId.toString())
.subscribe(response => {...})
response
将包含您的后端回报。
但我建议你的是,立即拨打每个HTTP电话。这可以通过使用Observable原型上的方法来完成,称为qazxsw poi。
如果使用forkJoin,则需要创建一个调用数组,如下所示:
forkJoin
这一次,响应将是每个和每个调用的数组,按照如何将它们放入数组中排序。
我希望这有帮助,如果没有,随时可以提出任何问题!
(这意味着您还需要从服务中删除整个const calls = [];
this.attachToDelete.forEach(element => {
calls.push(this.documentService.DeleteAttachment(element, this.newDocumentId.toString()));
});
Observable.forkJoin(calls).subscribe(responses => {...});
,因为如果您不这样做,您将不会返回可观察但订阅)