问题描述
限时送ChatGPT账号..我正在尝试通过迁移当前用 Angular1/AngularJS 编写的应用程序来提高我对 Angular2 的了解.
I am trying to improve my knowledge of Angular2 by migrating an application currently written in Angular1/AngularJS.
特别是一个功能让我难住了.我正在尝试复制一个功能,其中调用函数等待继续,直到它调用的函数完成一个承诺循环.在 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 => thisbined = {friends: res[0].friends, customer: res[1]});
这里有更多信息:http://www.syntaxsuccess/viewarticle/angular-2.0-and-http
这篇关于Angular2 Observable - 在继续之前等待多个函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论