Angular2观测 - 如何等待所有功能在一个循环中继续之前结束通话? [英] Angular2 Observable - how to wait for all function calls in a loop to end before proceeding?
问题描述
我想通过迁移目前写在Angular1的应用程序,以提高我Angular2知识
I am trying to improve my knowledge of Angular2 by migrating an application currently written in Angular1
在一个特别的功能已难倒我。我试图复制一个特征,其中一个调用函数等待继续,直到它被调用函数完成承诺的循环。在角一个功能我打电话基本上是这样的:
One feature in particular has me stumped. I am trying to replicate a feature where a calling function waits to proceed until the function it is calling has completed a loop of promises. In angular one the function I am calling looks basically like this:
. this.processStuff = function( inputarray, parentnodeid ) {
.
. var promises = [];
.
. var _self = this;
.
. angular.forEach( inputarray , function( nodeid ) {
.
. switch ( parentnodeid )
. {
. case ‘AAA’ : var component = _self.doMoreStuff( nodeid, parentnodeid ); break;
. case ‘BBB’ : var component = _self.doMoreStuff( nodeid, parentnodeid ); break;
. case ‘CCC’ : var component = _self.doMoreStuff( nodeid, parentnodeid ); break;
. default : var component = null;
. }
.
. promises.push( component );
.
. });
.
. return $q.all(promises);
. };
它包含一个foreach循环调用另一个函数(doMoreStuff)也返回一个承诺,其存储阵列中的所有返回的承诺。
It contains a forEach loop that calls another function (doMoreStuff) that also returns a promise and it stores all those returned promises in an array.
通过Angular1,当我打电话processStuff在另一个函数,我可以算系统等到processStuff在当时块进入code之前完成。 IE浏览器:
With Angular1, when I call processStuff in another function, I could count on the system waiting until processStuff completed before entering into the code in the then block. IE:
. service.processStuff( arraying, parentidarg )
. .then(function( data ) {
. . . .
processStuff的调用者等待所有doMoreStuff调用来完成,直到processStuff的调用者进入其当时块。
The caller of processStuff waits for all doMoreStuff invocations to complete until the caller of processStuff enters into its then block.
我不确定如何与Angular2和观测量来实现这一目标。我可以从这些帖子,为了模仿承诺,观测量基本上只使用订阅,而不是再看看:
I am unsure of how to achieve this with Angular2 and Observables. I can see from these posts that to mimic promises, Observables basically just use subscribe instead of then:
但我怎么等待在foreach循环中所有调用完成之前,我的系统可以继续?
But how do I wait for all invocations in the forEach loop to complete before my system can proceed?
大大预先感谢您的帮助,您可以分享。
Thank you greatly in advance for help you can share.
推荐答案
我一直forkJoin这样
I have been doing this with forkJoin
import {Observable} from 'rxjs/Observable';
Observable.forkJoin(
this.http.get('./friends.json').map((res: Response) => res.json()),
this.http.get('./customer.json').map((res: Response) => res.json())
).subscribe(res => this.combined = {friends:res[0].friends, customer:res[1]});
更多的一些信息在这里: http://www.syntaxsuccess.com/viewarticle /angular-2.0-and-http
这篇关于Angular2观测 - 如何等待所有功能在一个循环中继续之前结束通话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!