Angular循环遍历数组并使用forkJoin收集Observable

时间:2017-10-02 15:57:39

标签: angular typescript angular2-observables

我有一个方法,它获取一个字符串数组(tagArray: string[])作为输入。现在我循环遍历此数组并执行搜索(通过POST)到服务器以检查标记是否已存在于数据库中。

如果标记存在,则服务器返回相应的标记对象,并将其存储在另一个数组(searchFilter: { tags: Tag[] }[])中。

如果它不存在,则向服务器发出另一个POST请求,以在后端存储丢失的标记,之后,创建的标记对象将存储在searchFilter['tags']中。

performTagMatching(tagArray: string[]):any {
  for(let tagElem of tagArray) {
    // create search request for tag lookup
    const searchRequest: SearchRequest = { term: tagElem, operation: 'exact'};

    this.apiClientService.findTagByTitle(searchRequest).subscribe(
      (response) => {
        // Check tag search result for existence of tag
        if(response.length == 0) {
          // No tag found -> create tag and add to search tag list
          this.searchFilter['tags'].push(this.saveNewTag(tagElem));
        } else {
          // Tag found -> add to search tag list
          this.searchFilter['tags'].push(response[0]);
        }
      },
      (error) => {
        console.log(error);
      }
    );
  }
}

如何将它放在forkJoin中以便我可以返回forkJoin的Observable?

我有两个问题:

  1. 我需要' tagElem'在我离开for-loop

  2. 之后我无法访问的响应中
  3. 我不知道如何将Observables推送到数组中,返回方法调用者

1 个答案:

答案 0 :(得分:1)

将您的http调用与for循环分开,并将其作为单独的函数调用。

1000