【问题标题】:Angular loop through array and collect Observables with forkJoinAngular 循环遍历数组并使用 forkJoin 收集 Observables
【发布时间】:2018-03-13 17:50:04
【问题描述】:

我有一个方法可以获取字符串数组(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 循环后我无法再访问它

  2. 我不知道如何将 Observables 推入一个数组并返回给方法调用者

【问题讨论】:

    标签: angular typescript angular2-observables


    【解决方案1】:

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

    performTagMatching(tagArray: string[]): any {
        for (let tagElem of tagArray) {
            // create search request for tag lookup
            const searchRequest: SearchRequest = {
                term: tagElem,
                operation: 'exact'
            };
    
            this.callMactchFunc(tagElem)
        }
    }
    
    private callMactchFunc(tagElem) {
        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 时仍然可以访问 tagElem?
    猜你喜欢
    • 2020-12-22
    • 2021-09-12
    • 2018-06-17
    • 2020-09-10
    • 2021-02-11
    • 1970-01-01
    • 2017-08-16
    • 2015-06-09
    • 1970-01-01
    相关资源
    最近更新 更多