angular2异步函数执行

时间:2017-06-14 15:52:22

标签: angular asynchronous

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

1 个答案:

答案 0 :(得分: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;
    });

正如您所注意到的,您需要订阅一个observable才能触发调用。

相关问题