Ben*_*ren 30 javascript observable angular-promise angular
我试图通过迁移当前用Angular1编写的应用程序来提高我对Angular2的了解
特别令我难过的一个特点.我试图复制一个功能,其中一个调用函数等待继续,直到它调用的函数完成了一个promises循环.在有角度的一个中,我调用的函数看起来基本上是这样的:
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);
};
Run Code Online (Sandbox Code Playgroud)
它包含一个forEach循环,它调用另一个函数(doMoreStuff),该函数也返回一个promise,它将所有返回的promises存储在一个数组中.
使用Angular1,当我在另一个函数中调用processStuff时,我可以指望系统等到processStuff完成后再进入then块中的代码.IE:
service.processStuff( arraying, parentidarg )
.then(function( data ) {
...
Run Code Online (Sandbox Code Playgroud)
调用者processStuff等待所有doMoreStuff调用完成,直到调用者processStuff进入其then块.
我不确定如何使用Angular2和Observables实现这一目标.我可以从这些帖子中看到,为了模仿承诺,Observables基本上只使用subscribe而不是:
但是,如何forEach在我的系统继续之前等待循环中的所有调用完成?
TGH*_*TGH 67
我一直用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]});
Run Code Online (Sandbox Code Playgroud)
这里有更多信息:http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
| 归档时间: |
|
| 查看次数: |
37610 次 |
| 最近记录: |