2017-06-14 102 views
0

我想一起执行两个语句,但不是异步执行。有没有办法在angular2之前function 2之前执行function 1angular2异步函数执行

+8

请张贴演示您尝试完成的代码,您尝试过的以及失败的位置。你的问题没有提供足够的信息。 –

回答

1

我们可能需要更多的信息,但假设你有2个http调用,并且你想让它们“同步”(一个是第一个,然后是第二个)。 我会建议使用ReactiveX JavaScript,您可以通过包括导入:

import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/observable/mergeMap'; 

随着mergeMap操作符,你可以开始了“第二个任务”(新observable)作为输入的第一个的结果。

因此,例如,我需要检查地址,然后再更新我的用户配置文件。我有2个http调用;一个是地址检查,另一个用于更新用户的个人资料,所以我会做:

this.http.get(geolocationGoogleUrl, this._customAddress) 
    .mergeMap((location: any)=>{ // First http response 
     console.log(location); 
     // Do your stuff before second call 

     return this.http.patch(patchUrl, localAddress); // Use frist http response as input 
    }).subscribe((updatedUser)=>{ // Second http response 
     this._user = updatedUser; 
    }); 

当你注意到了,你需要申请一个可观察的,以触发呼叫。