Angular2 - 如何在组件中链接异步服务调用(http请求)? [英] Angular2 - How to chain async service calls (http requests) in a component?

查看:811
本文介绍了Angular2 - 如何在组件中链接异步服务调用(http请求)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个首先需要调用POST服务的组件。然后在同一个组件中,我想等到POST完成,调用另一个获取数据的服务。

I have a component which first need to call a service that POST something. Then in the same component I want to wait until the POST is done, to call another service which GETs data.

如何进行GET调用等待POST调用完成?

How can I make the GET call wait for the POST call to finish?

在new-version.component.ts中:

In new-version.component.ts:

private createNewVersion(value) {
    ...

    // create new version, then call on all available versions

    // POST call
    this._newVersionService.createNewVersion(vnr);

    // GET call
    this._versionService.getAvailableVersions(); 

    ...
}

在新版本中。 service.ts:

In new-version.service.ts:

export class NewVersionService {

response$: Subject<any>;

constructor(private _http: Http) {
    this.response$ = new BehaviorSubject<any>(null);
 }

public createNewVersion(versionNr) {    
    this._http.post('http://localhost:8080/services/' + versionNr, null, {
        method: 'POST',
    })
    .subscribe(response => {
        this.response$.next(response.status);
    },
    error => console.error(error));
}

谢谢!

推荐答案

当呼叫返回 Promise 链时,

someFunction() {
  return returnsPromise()
    .then(result => doSomethingNext())
    .then(result => doSomethingAfterThat());
}

确保您有返回返回该链的 Promise ,因此 someFunc()的调用者也有机会为额外的工作计时在 doSomethingAfterThat()完成后执行。

Ensure you have a return that returns the Promise of that chain so the caller of someFunc() also has a chance to time additional work to execute after doSomethingAfterThat() is completed.

当一个调用返回一个 Observable 然后使用完成回调

When a call returns an Observable then use the complete callback

someFunction() {
  return returnsObservable()
    .subscribe(
      event => doForEachEvent(),
      error => handleError(),
      () => doSomethingNext()
          .then(result => doSomethingAfterThat());
}

doSomethingNext()在最后一个事件和<$ c $之后执行c> doSomethingAfterThat()再次与然后()链接,以显示如何混合observable和promise。 doSomething()

doSomethingNext() is executed after the last event and doSomethingAfterThat() is again chained with then() to show how to mix observable and promise. doSomething().

这篇关于Angular2 - 如何在组件中链接异步服务调用(http请求)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆