代码之家  ›  专栏  ›  技术社区  ›  T. Evans

使用forEach Angular 4的多个POST请求

  •  1
  • T. Evans  · 技术社区  · 8 年前

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

    以下是我为找到可能的解决方案而查看的其他堆栈问题:

    Http request in forEach function. Angular2

    Angular http post on loops

    Chaining http calls in angular 2 in a for loop

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

    服务输电系统

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

    谢谢你的帮助。

    1 回复  |  直到 8 年前
        1
  •  6
  •   Renaud T.    8 年前

    这是你想要的( Http request in forEach function. Angular2

    不能从返回值,因为它将退出函数( 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)
    }