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.

1 Answer

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(); } } 
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like