仅在完成角度5中的线程执行后,如何调用函数?

时间:2019-01-31 07:37:07

标签: angular promise rxjs angular5

  

我正在尝试在线程之后调用一个函数。但是功能是   在完成线程之前被调用。我需要在哪里更改?

this._listService.getListById(this.userName)
  .subscribe((response: any) => {     // getting proper response.
    if (response) {
      this._listServiceMod.loadListModel(response); // thread
      this.filterList();
    }
  });



 loadListModel(data:any) {
        const promise = this._listItemService.run(
                        this.loadListItem,
                        {
                            constants: appConstants
                        });
        promise.then((updatedAuthList) => {
            ....
            ....
            this._listItemService.terminate(promise);
        }).catch(e => {
        });;
    }




  filterList(){
  console.log('Inside Filter List')  // prints before completing thread.
  }

4 个答案:

答案 0 :(得分:1)

使用异步

尝试这种方式
this._listService.getListById(this.userName)
.subscribe((response: any) => {    
  if (response) {
     this.modelOpen(response);
  }
});

filterList(){
  console.log('Inside Filter List')
}

async modelOpen(response) {
   await this._listServiceMod.loadListModel(response);
   this.filterList();
}

Async

答案 1 :(得分:1)

如果filterList不依赖于先前方法的输出,则可以利用RxJs的mergeMap处理这种情况。

this._listService.getListById(this.userName).pipe(
  mergeMap(response => this._listServiceMod.loadListModel(response))
).subscribe(response => {
  this.filterList();
});

答案 2 :(得分:1)

将您的loadListModel方法更改为遵循。

loadListModel(data:any): Promise<any> {
   let promise = this._listItemService.run(
       this.loadListItem,
       {
          constants: appConstants
       })
   return promise.then((updatedAuthList)=> {
       this._listItemService.terminate(promise);
       return true;
   });
}

您现在可以将返回的promise转换为可观察对象,并在rxjs中使用mergeMap来合并两个可观察对象

this._listService.getListById(this.userName)
 .pipe(
    mergeMap(response => {
      if(response) {
        // Getting the promise
        let promise = this._listServiceMod.loadListModel(response);

        // Converting the promise to an observable by using rxjs's from
        return from(promise);
      } else {
        return false;
      }
    )
 )
 .subscribe((res) => {
    // Finally call the filterList
    if(res)
       this.filterList();
 });

查看此有效的stackblitz

答案 3 :(得分:1)

将loadListModel更改为Observable:

this._listServiceMod.loadListModel(response).pipe(
  tap(() =>  this.filterList())
).subscribe()