简体   繁体   中英

wait for a promise in success() of an observable subscription

Disclaimer: this is part of my practice for a class I am taking but my instructor knows if that matters.

Basically, I am required to write a method in my component. All other services are provided for. First, there is an observable i subscribe too. It emits a value. Then I have to pass that value to a promise which returns an array.

Then I have to console.log('done') when it is all finished. Now my problem is that the onComplete ie () of the subscription while the promises are still getting resolved. Here is my attempt. recordList does contain the correct result at last but it the complete piece is reached, outputting 'done' to the console first.

let recordList = [];

public loadData() {

  let vm: any = this;

    this.dataService.getRecord().subscribe(
      record => {
       // record is now a single dictionary object
       // {'type': 'bookkeeping', 'id': 1}

       // for each record type, get its list of attached data

       record['data'] = []; // in case it has not record

        vm.dataService.recordDetails(record.id).then(recordData => {
            // recordData is an array
         record['data']  = recordData
          vm.recordList.push(record);
        });
      },
      err => {
        console.log("error getting record");

      },

      () => {
        console.log('done')
      }
    )

}

Use Observable.fromPromise,

 this.dataService.getRecord().switchMap(record => {
   record['data'] = [];
   return Observable.fromPromise(vm.dataService.recordDetails(record.id));
 }).subscribe((recordData ) => {
 record['data']  = recordData
   vm.recordList.push(record);
 });

You need return a Promise and resolve or reject:

    loadData(): Promise<any> {

        return new Promise((resolve, reject) => {
           this.dataService.getRecord().subscribe(d => {
...
             resolve(d)
            },
            (err: HttpErrorResponse) => {
             ...
                reject(err.error);

            });
        });
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM