简体   繁体   English

等待观察到的订阅成功()中的承诺

[英]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. 然后,我必须将该值传递给一个返回数组的Promise。

Then I have to console.log('done') when it is all finished. 然后,我必须在全部完成后使用console.log('done')。 Now my problem is that the onComplete ie () of the subscription while the promises are still getting resolved. 现在我的问题是,在承诺仍得到解决的同时,订阅的onComplete即()。 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. recordList最终包含正确的结果,但是它达到了完整的结果,首先将“ done”输出到控制台。

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, 使用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);

            });
        });
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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