T. *_*ans 1 javascript foreach http-post rxjs angular
所以我试图在 Angular 中从数组中执行 POST 请求。基本上,当用户选择列表中的多个项目时,他们可以“解锁”每个项目。所以我遇到的问题是如何使用 forEach 进行 POST。我能够使用 forLoop 执行 POST,但问题是当它执行一个 POST 时,它不会执行另一个。有人可以指出我做错了什么,或者是否有更好的解决方案来解决这个问题?
以下是我查看的其他堆栈问题以找到可能的解决方案:
组件.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);
}
Run Code Online (Sandbox Code Playgroud)
服务.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());
});
}
Run Code Online (Sandbox Code Playgroud)
它与 Observable 有关还是可以用 Promises 处理?
感谢您的帮助。
小智 6
这是您查找的内容(forEach 函数中的 Http 请求。Angular2)和您的代码之间的混合。
你不能从 a 返回一个值,因为它会退出函数(在 `forEach` 函数中 `return` 关键字是什么意思?)
希望能帮助到你
postUnlock(locked){
//create an array of Observables
let allQueries = locked.map(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());
});
//return a new observable that will emit all the http results
return Observable.forkJoin(allQueries)
}
Run Code Online (Sandbox Code Playgroud)