So I am trying to do a POST request in Angular from an array. Basically, when a user selects multiple items in a list they can "unlock" each item. So the issue I am running into is how to do a POST with a forEach. I was able to do a POST with a forLoop but the issue is that when it does one POST it does not do the other one. Can someone please point out what I am doing wrong or if there is a better solution to this problem?
Here are the other Stack questions I looked through to find a possible solution:
Http request in forEach function. Angular2
Chaining http calls in angular 2 in a for loop
component.ts
locked: Array<any> = [];
// Unlock
unlock() {
let observer = {
next(data) {
data => console.log(data)
},
error(error) {
return new Error('Post Error');
},
complete() {
console.log("Completed");
// window.location.reload();
}
}
// On unlock send lock data to Service for POST
this.http.postUnlock(this.unlocked).subscribe(observer);
}
service.ts
// POST to UNLOCK RESOURCES
postUnlock(locked) {
let headers = new Headers();
headers.append( 'Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
locked.forEach((lock) => {
let newBody = JSON.stringify(lock);
let auth = lock.AuthID;
let form = lock.FormName;
let options = new RequestOptions({ headers: headers, method: 'post', body: newBody });
let newUrl = this.url + `?authid=${auth}&formname=${form}`;
// POST to URL
return this.http.post(newUrl, options).map(res => res.json());
});
}
Is it something that has to do with the Observable or is this something that can be handled with Promises?
Thank you for your help.