具有多种订阅方法的角模态

时间:2018-12-18 14:42:51

标签: angular rxjs bootstrap-modal

我正在努力弄清这一点,我读到嵌套订阅是不好的。 我有一个模式窗体,该窗体从服务中获取要选择的项目列表,然后一旦选择了一个项目,模式就会关闭,然后我要将选择发送回服务。我已经阅读了很多关于Stackoverflow的问答,但是我不确定该怎么做?

public click_AddModalItem(includeAll: boolean) {
    // Modal InitialState Variables
    const initialState = {
        title: 'Select from List',
        dataList: {},
    };
    // Get Source Data list from backend
    this.service.getSourceData(includeAll)
    .subscribe(
        data => {
            // Set Source data for Modal form
            initialState.dataList = data;
            this.modalRef = this.modalService.show(FrmSearchComponent, { initialState });
            this.modalRef.content.onClose
            .subscribe(modalResult => {
                // Get Modal result and add it to the backend
                console.log('Modal Result');
                console.log(modalResult);
                this.service.addSelectedItem(modalResult)
                .subscribe(
                    apiResponse => {
                    console.log(apiResponse);
                });
        });
    });
}

3 个答案:

答案 0 :(得分:0)

如果它们是彼此独立的三个独立的任务/可观察对象,则考虑使用forkJoin

let observable1(param1);
let observable2(param2);
let observable3(param3);

let joinedObservables = forkJoin(observable1, observable2, observable3).subscribe(x => {
  let result1 = x[0];
  let result2 = x[1];
  let result3 = x[2];

  ...
});

如果它们的结果相互依赖,则可以使用switchMapflatMapmergeMapexhaustMap(检查差异)

let resultObservable =  return this.observable1().pipe(mergeMap((param1) => {
  return this.observable2().pipe(map((param1) => {

    ....        

    return <result>;
  }));
}));

resultObservable.subscribe(x => {
   ...
});

答案 1 :(得分:0)

您可以使用mergeMapswitchMap来压平它

类似这样:

public click_AddModalItem(includeAll: boolean) {
    // Get Source Data list from backend
    this.service
      .getSourceData(includeAll)
      .pipe(
        map(dataList => ({
          title: 'Select from List',
          dataList
        })),
        switchMap(initialState =>
          this.modalService.show(FrmSearchComponent, { initialState })
        ),
        tap(modalRef => (this.modalRef = modalRef)),
        switchMap(modalRef => modalRef.content.onClose),
        switchMap(modalResult => this.service.addSelectedItem(modalResult))
      )
      .subscribe(apiResponse => {
        console.log(apiResponse);
      });
}

答案 2 :(得分:0)

感谢Simonare,您的代码建议行得通,但做了一些小的更改。

const resultObservable = this.service.getSourceData(includeAll)
    .pipe(mergeMap(param1 => {
        initialState.dataList = param1;
        this.modalRef = this.modalService.show(FrmSearchComponent, {initialState});
        return this.modalRef.content.onClose
        .pipe(map(param2 => {
            return param2;
        }));
}));
resultObservable.subscribe(result => {
    console.log(result);
});