Angular2 - 如何在组件中链接异步服务调用(http请求)?

时间:2016-02-03 09:54:40

标签: http asynchronous angular chaining

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

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

在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(); 

    ...
}

在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));
}

谢谢!

5 个答案:

答案 0 :(得分:5)

当一个呼叫通过

返回一个Promise链时
someFunction() {
  return returnsPromise()
    .then(result => doSomethingNext())
    .then(result => doSomethingAfterThat());
}

确保您有return返回该链的Promise,以便someFunc()的来电者也有机会在doSomethingAfterThat()完成后执行额外的工时

当来电返回Observable时,请使用complete回调

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

doSomethingNext()在最后一次event之后执行,doSomethingAfterThat()再次与then()链接,以显示如何混合观察和承诺。 doSomething()

答案 1 :(得分:1)

您应该能够concat获得序列,reduce来收集发出的值:

var a = this._newVersionService.createNewVersion(vnr);
var b = this._versionService.getAvailableVersions(); 

Rx.Observable.concat(a, b).reduce((acc:Array<any>, x:any) => {
    acc.push(x); return acc;
}, []).subscribe(t=> { 
      var firstEmitted = t[0];
      var secondEmitted = t[1];
});

答案 2 :(得分:0)

你可以这样做: 将createNewVersion更改为:

public createNewVersion(versionNr) {
 return this._http.post('http://localhost:8080/nod_inspection_plugin/services/' + versionNr, null, {
    method: 'POST',
 });
}

然后在你的电话中:

this._newVersionService.createNewVersion(vnr).subscribe(response=> {
 this._versionService.getAvailableVersions(); 
}, error => console.error(error));

答案 3 :(得分:0)

执行相同操作的另一种方法是subscribe中的new-version.component.ts并在GET请求中为您POST提出请求,即检查您的POST是否POST请求是否正确完成 如果是GET已正确完成,请致电 private createNewVersion(value) { ... // create new version, then call on all available versions // POST call this._newVersionService.createNewVersion(vnr) .subscribe((res) => { if(res){ console.log(res); if (---Post request done properly check via status or something else here----{ CALL YOUR GET REQUEST HERE..... // GET call this._versionService.getAvailableVersions(); } else { DO something else whatever you want.... } } }); ... } 请求。如下:

在new-version.component.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/nod_inspection_plugin/services/' + versionNr, null, {
        method: 'POST',
    })
    .map(response => {
        return [{status: response.status, json: response.json()}];
    },
    error => console.error(error));
}

在new-version.service.ts中:

http

有关get '/cities/:city/:section' => 'cities#show', as: 'city_section_slug' get '/cities/:city/:section/:subsection' => 'cities#show', as: 'city_subsection_slug', :constraints => { :subsection => /[^\/]*/ } 请求的更多信息,您可以read here

答案 4 :(得分:0)

最好在这里使用switchMap()

const versions$ = this._newVersionService.createNewVersion(vnr)
                 .switchMap(response => this._versionService.getAvailableVersions());

versions$.subscribe(response2 => this.versions = response2)

但问题是如果你在第一次解决之前再发一个POST请求,之前的请求就会被取消。