Home > Blockchain >  How to open dialog and pass data from BehaviorSubject?
How to open dialog and pass data from BehaviorSubject?

Time:11-03

There is a users subject:

public users$ = new BehaviorSubject();

Inside component I get users as observer:

class Component {
   public users$: Observable<User>;
   public move() {
        if(this.users$.length) {
           this.dialog.open(DialogComponeent, {});
        }
   }
}

So, I need to get value from users$ in method move() and pass it to dialog window. How to do that?

CodePudding user response:

You can access to the value of BehaviorSubject directly at this moment. Your code should be like this:

Simple way:

class Component {
   public users$: Observable<User>;
   public move() {
        if(this.users$.value.length) {
           this.dialog.open(DialogComponeent, {
             data: this.users$.value
           });
        }
   }
}

More convenient way:

class Component {
   public users$: Observable<User>;
   public move() {
        this.users$.pipe(
          first(),
          filter(value => value.length),
        ).subscribe(value => 
          this.dialog.open(DialogComponeent, {
             data: value
          })
        );
   }
}
  • Related