Angular2 - How to chain async service calls (http requests) in a component?

前端 未结 5 2112
刺人心
刺人心 2020-12-17 18:59

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

相关标签:
5条回答
  • 2020-12-17 19:36

    You can do like this: Change createNewVersion to:

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

    Then in your call:

    this._newVersionService.createNewVersion(vnr).subscribe(response=> {
     this._versionService.getAvailableVersions(); 
    }, error => console.error(error));
    
    0 讨论(0)
  • 2020-12-17 19:38

    Better use switchMap() here.

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

    But the problem will be if you make another POST request before first has been resolved, the previous request will get cancelled.

    0 讨论(0)
  • 2020-12-17 19:48

    You should be able to concat to achieve sequence, and reduce to collect the emitted values:

    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];
    });
    
    0 讨论(0)
  • 2020-12-17 19:50

    When a call returns a Promise chain the calls with

    someFunction() {
      return returnsPromise()
        .then(result => doSomethingNext())
        .then(result => 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.

    When a call returns an Observable then use the complete callback

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

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

    0 讨论(0)
  • 2020-12-17 19:50

    Another way to do the same is to subscribe in the new-version.component.ts and call you GET request from within the POST request i.e check whether your POST request is done Correctly or not if yes POST is done Properly then call you GET request. As below:

    In new-version.component.ts:

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

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

    for more info related to http request you can read here.

    0 讨论(0)
提交回复
热议问题