使用forEach Angular 4的多个POST请求

时间:2017-10-03 18:47:45

标签: javascript angular foreach http-post rxjs

所以我试图从数组中在Angular中执行POST请求。基本上,当用户选择列表中的多个项目时,他们可以“解锁”每个项目。所以我遇到的问题是如何使用forEach进行POST。我能够使用forLoop进行POST,但问题是当它执行一个POST时它不会执行另一个POST。有人可以指出我做错了什么或者是否有更好的解决方案来解决这个问题?

以下是我查找可能解决方案的其他Stack问题:

Http request in forEach function. Angular2

Angular http post on loops

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());
    });
  }

是否与Observable有关,或者这是否可以使用Promises处理?

感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

这是您查找的内容(Http request in forEach function. Angular2)与您的代码之间的混合。

你不能从a中返回一个值,它将退出函数(What does `return` keyword mean inside `forEach` function?

希望有所帮助

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)
}