javascript - 需要知道监听 rxjs Observable 的函数何时收到答案

标签 javascript angular rxjs observable rxjs5

如何使用在 if 语句中返回的可观察对象上启动监听器的方法?

我在一个 Angular 5 项目中,我在一个带有时间线的组件中进行了这种设置,双击打开一个模式,您可以在该模式中输入要创建的项目的名称.

对于模态,我使用了 this answer 的修改版本。 (我需要更多最新的语法和导入)。

现在一切都差不多了,这是我的设置,

(打开模态的时间轴组件):

@Component({
  selector: 'app-planning',
  templateUrl: './planning.component.html',
  styleUrls: ['./planning.component.css']
})
export class PlanningComponent implements AfterViewInit {

  options = {
    onAdd: (item, callback) => {
      if(this.timeline.getCurrentTime() > item.start){

        this.errorTimelineItemModal();
        callback(null);

      } else {
          if (this.createNewTimelineItemModal()) { // <-- currently I have no return but
                                                  //   having one would be meaningless
                                                 // anyways because the if wouldn't wait
                                                // for the observable response and as a
                                               // result, it would always assess false.
          callback(item);

        } else callback(null);
      }
    }
  }


  constructor(
      private _element: ElementRef,
      private modalService: BsModalService
  ) {}

  ngAfterViewInit(){
    this.container = this._element.nativeElement.querySelector('#timeline');
    if (!this.items) {
      this.items = new vis.DataSet(this.mydataset);
      this.timeline = new vis.Timeline(this.container, this.items, this.groups, this.options);
    }
  }

  createNewTimelineItemModal() {
    const initialState = {
      title: 'Ajouter',
      multipleChoice: 'Bid',
      choices: ['Bid', 'D.C.', 'Kickoff'],
      accceptBtnName: 'Ajouter',
      closeBtnName: 'Annuler',
    };
    this.bsModalRef = this.modalService.show(Modal, {initialState});
    this.bsModalRef.content.onClose.subscribe(result => {
        this.createItemResult = result;
        console.log(JSON.stringify(result));
    })
  }

  updateTimelineItemModal(name) {
    const initialState = {
      title: 'Nouveau Nom ?',
      itemCurrentName: name,
      accceptBtnName: 'Rennomer',
      closeBtnName: 'Annuler',
    };
    this.bsModalRef = this.modalService.show(Modal, {initialState});
    this.bsModalRef.content.onClose.subscribe(result => {
        this.createItemResult = result;
        console.log(JSON.stringify(result));
    })
  }

  deleteTimelineItemModal() {
    const initialState = {
      title: 'Êtes-vous sûr de vouloir supprimer cet element?',
      accceptBtnName: 'Supprimer',
      closeBtnName: 'Annuler',
    };
    this.bsModalRef = this.modalService.show(Modal, {initialState});
    this.bsModalRef.content.onClose.subscribe(result => {
        this.createItemResult = result;
        console.log(JSON.stringify(result));
    })
  }

  errorTimelineItemModal() {
    const initialState = {
      title: 'Erreur',
      list: ['Désolé, créer des éléments avant la date d\'aujourd\'hui est désactivé']
    };
    this.bsModalRef = this.modalService.show(Modal, {initialState});
    this.bsModalRef.content.onClose.subscribe(result => {
        this.createItemResult = result;
        console.log(JSON.stringify(result));
    })
  }
}

(模态组件):

export class Modal implements OnInit {

  onClose: Subject<Object>;

  constructor(
    private formBuilder: FormBuilder,
    public _bsModalRef: BsModalRef) {}

  ngOnInit(): void {
    this.onClose = new Subject();
  }

  public onConfirm(): void {
    this.onClose.next(true);
    this._bsModalRef.hide();
  }

  public onCancel(): void {
     this.onClose.next(false);
     this._bsModalRef.hide();
  }
}

正如你所看到的,我通过验证或不验证模式得到了答案。我可以控制台记录它。

现在我陷入了困境。如何让代码执行停止,直到该方法收到可观察值,以便在 if 内正确评估?

这实际上对于正确执行我的代码非常重要,因为您可能已经注意到的 callback(null);callback(item); 是语法人们必须要么完成项目创建,要么阻止它。

参见:http://visjs.org/docs/timeline/#Methods

我已经将其与警报一起使用,但我正在尝试切换到具有更多功能和更清洁的东西。

最佳答案

如果我理解正确的话,您需要同步两个单独的事件。这样做通常是一种不好的做法。

尝试重新组织您的代码。这是一个异步流程,因此您应该将该流程划分为可以单独发生的子“事务”。

  1. 分离打开模式的逻辑。
  2. 等待用户输入数据
  3. 处理模态中的答案。

类似这样的事情:

  createNewTimelineItemModal() {
    const initialState = {
    ... 

    this.bsModalRef.content.onClose.subscribe(result => {
        this.createItemResult = result;
        this.continueToCreateItem(result);
      });
    }

  private continueToCreateItem(result: any){
    <insert your code here>
  }

或者其他解决方案可以返回可观察对象并在 onAdd 中处理它

options = {
    onAdd: (item, callback) => {
    ...
          this.createNewTimelineItemModal().subscribe(result => {
             if(result is something){
              callback(item);
             } else callback(null);
         }
      }
    }
  }

“停止”该过程是一种非常糟糕的做法,但可以通过 Promise 来实现对象。

this.myPromiseReturningMethod(params).then(() => {

但这会暂时阻止您的所有应用程序(用户无法执行任何操作),因此我建议改为更改结构。

关于javascript - 需要知道监听 rxjs Observable 的函数何时收到答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49533100/

相关文章:

php - 单击相同的按钮打开模型,然后提交表单

angular - 覆盖 Angular Material 主体排版

angular - 如何使用 matDialog Close 而不是父对话框关闭子/嵌套对话框

Javascript 函数无法获取高度 css 属性

javascript - Amazon Alexa Skill Lambda Node JS - Http GET 不工作

angular - Ag-grid 和 Angular2 使用 angular-cli

arrays - RxJS 限制和返回响应结果数组的最佳方式

javascript - 派生流的最新组合

Angular HttpClient 映射对象的可观察数组

javascript - Function、Array 和 Object 构造函数的 length 属性是什么?