【问题标题】:Loop through/concat list of http observables using Typescript使用 Typescript 循环/连接 http observables 列表
【发布时间】:2018-01-22 15:33:32
【问题描述】:

我有一个属性列表,需要作为更大的 mergeMap 操作的一部分提交。

this.customFeedsService.postNewSocialMediaFeed(this.newFeed)
            .mergeMap( newFeed => this.customFeedsService.postFeedProperties( newFeed.Id, this.feedProps))
            .mergeMap(newProps => this.customFeedsService.preloadSocialMediaFeed(newProps.FeedId))
            .subscribe(data => console.log(data), err => console.log);

在我的服务中,我循环遍历属性以创建返回到 mergeMap 操作的单个 Observable。

public postFeedProperties( feedId: number, props: FeedPropertyApi[] ): Observable<any> {
    let observeGroup = new Observable<any>();
    for(let prop of props){
        prop.FeedId = feedId;
        observeGroup.concat(this.apiService.postData(this.feedPropertyApiUrl, prop, true)
            .map(res => res.json()));
    }

    return observeGroup
    // return this.apiService.postData(this.feedPropertyApiUrl, props[0], true)
    //          .map(res => res.json()).concat(this.apiService.postData(this.feedPropertyApiUrl, props[1],true)
    //          .map(res => res.json())).concat(this.apiService.postData(this.feedPropertyApiUrl, props[2], true)
    //          .map(res => res.json()));
}

现在,当我运行注释部分时,一切都按预期工作。但是,当我运行循环时,我得到一个Cannot read property 'subscribe' of undefined 错误。我在循环中做错了什么?

【问题讨论】:

标签: angular loops typescript rxjs observable


【解决方案1】:

您是否尝试过在 for 循环中使用关键字“as”而不是“of”

for(let prop as props) {...}

否则您能否提供更多关于代码在哪里中断以及在第一次迭代时中断的描述?

【讨论】:

    【解决方案2】:

    感谢 Eliseo 的回答。以下是我实现代码的方式。

    let observeGroup: Observable<any>[] = [];
        for(let prop of props){
            prop.FeedId = feedId;
            observeGroup.push(this.apiService.postData(this.feedPropertyApiUrl, 
            prop, true)
                .map(res => res.json()));
        }
    return Observable.forkJoin(observeGroup).map(res => res);
    

    【讨论】:

      猜你喜欢
      • 2016-05-18
      • 2018-06-26
      • 1970-01-01
      • 2013-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多