msqar
msqar

Reputation: 3040

Get ObservableInput value and avoid subscription to it

I got an ObservableInput in my Angular component, and also a Subject button that on press, I get the input value, and call another observable, then subscribe to it to use the returned data.

But the problem is that whenever this input changes, it triggers the (onClick) function that isn't meant to be triggered without clicking as it's subscribed to the input automatically because I'm using switchMap.

How can I prevent this from happening?

class SomeComponent {
   @ObservableInput @Input() name$: Observable<string>;
   private clickSubject = new Subject<Event>();

   constructor(private _someService: Service) {
      this.clickSubject.pipe(
          switchMap(() => this.name$),
          switchMap((name) => this._someService.getUserByName(name))
      ).subscribe((data: UserData) => {
          // Work around with data here.
      });
   }

   onUserClick(): void {
       clickSubject.next();
   }
}

I read that I could use "merge()" from RxJS, but I can't seem to find a way to make it work. mergeMap also returns an Observable but subscribes to name$ which is not desired.

I need to only get current name$ value without subscribing to it so whenever it changes, it doesn't trigger whatever is on subscribe block.

Thanks.

Upvotes: 0

Views: 605

Answers (1)

Barremian
Barremian

Reputation: 31125

I don't see the need here to make the name$ an @ObservableInput. If it's only use is to be used an a parameter to the HTTP request, it could just be a plain Angular @Input property. It could then be accessed inside the switchMap using this.name.

class SomeComponent implements OnInit {
   Input() name: string;
   private clickSubject = new Subject<Event>();

   ngOnInit(private _someService: Service) {
     this.clickSubject.pipe(
       switchMap(() => this._someService.getUserByName(this.name))
     ).subscribe((data: UserData) => {
       // Work around with data here.
     });
   }

   onUserClick(): void {
     clickSubject.next();
   }
}

Upvotes: 1

Related Questions