简体   繁体   中英

How to use MatDialog.open inside operator iif

I just ran into the following issue

function doMagic(foo: boolean) {
    return iif(
        () => foo,
        this.dialog.open(MyComponent).afterClosed(),
        of(true)
    ).pipe( .... );
}

So, if foo === true I want to open the dialog, if false, I don't and true is emitted.

Now, the problem with this code is, that no matter what foo is, the dialog will always open. Should I replace iif with an if/else, something like this

function doMagic(foo: boolean) {
    let stream = of(true);

    if (foo) {
        stream = this.dialog.....
    }

    stream.pipe(...);
}

or is there a way I can fix my initial code, such that, for example, the open function behaves more as a stream.

Using iif introduces unnecessary complication. The only point of using it is when you need to delay the execution of the condition until the moment of subscription. Your example doesn't need that and even if it did, using defer with a condition inside of it will be cleaner and more flexible. In fact, if you check the source , you'll see that iif just wraps defer . IMO, just avoid the iif operator entirely.

Your second example is fine, and you could make things a bit more concise with the conditional ternary operator.

doMagic(foo: boolean) {
  const stream$ = (foo) ? this.dialog.open(MyComponent).afterClosed() : of(true);
  return stream$.pipe(/* .... */);
}

Here's an example using defer where foo is some class variable. When somebody subscribes to the stream, the value of foo is checked then.

doMagic() {
  return defer(() => (this.foo) ? this.dialog.open(MyComponent).afterClosed() : of(true))
    .pipe(/* .... */);
}

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