Angular2 Observable-等待多个函数调用,然后继续 [英] Angular2 Observable - Await multiple function calls before proceeding
问题描述
我试图通过迁移当前用Angular1/AngularJS编写的应用程序来提高对Angular2的了解.
I am trying to improve my knowledge of Angular2 by migrating an application currently written in Angular1/AngularJS.
我特别难过一个功能.我正在尝试复制一个功能,在该功能中,调用函数将等待继续进行,直到它所调用的函数完成了一个Promise循环为止.在AngularJS中,我正在调用的函数基本上如下所示:
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 AngularJS, 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.
使用AngularJS,当我在另一个函数中调用processStuff
时,我可以指望系统等到processStuff
完成,然后再在then块中输入代码:
With AngularJS, 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:
service.processStuff( arraying, parentidarg )
.then(function( data ) {
...
processStuff
的调用者等待所有doMoreStuff
调用完成,直到processStuff
的调用者进入其then
块.
The caller of processStuff
waits for all doMoreStuff
invocations to complete until the caller of processStuff
enters into its then
block.
我不确定如何使用Angular2和Observables实现此目的.从这些帖子中我可以看到,模仿承诺,Observables基本上只使用subscribe()
而不是then()
:
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()
:
Angular 1.x $ q到Angular 2.0 beta
但是在我的应用程序可以继续之前,如何等待forEach
循环中的所有调用完成?
But how do I await all invocations in the forEach
loop to complete before my application can proceed?
推荐答案
我一直在使用forkJoin
I have been doing this with forkJoin
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
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 Observable-等待多个函数调用,然后继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!