I have made some slight modifications to your code:
1 - Firstly, we need to add a User button in the template And
<button #createUserBtn mat-flat-button color="primary" [disabled]="userStatus == 'USER_EXISTS_ON_CURRENT_ACCOUNT'"> CreateUser </button>
2 - Next step is to access the Create User button in the .ts file
@ViewChild('createUserBtn', {static:true}) button;
3 - We create a variable clicks$
to store click events
clicks$: Observable<any>;
4 - In the ngOnInit function: Initialize the clicks$
variable to listen for click events
this.clicks$ = fromEvent(this.button.nativeElement, 'click');
5 - Also in the ngOnInit function: On every click event from click$
, we will utilize exhaustMap
The benefit of exhaustMap is that once the first (outer observable) event is triggered, it will stop
listening to events(Outer Observable) until it completes its inner observable
In our scenario, when the user clicks on the button for the first time(event), the exhaustMap
will cease listening to the button click events until it finishes our API call createUser()
. This API call observable will be managed using the handleResponse()
method.
ngOnInit() {
this.clicks$ = fromEvent(this.button.nativeElement, 'click');
const result$ = this.clicks$.pipe(
tap(x => console.log('clicked.')),
exhaustMap(ev => {
console.log(`processing API call`);
return this.createUser();
})
);
result$.subscribe(this.handleResponse());
}
Make the Create User API Call
createUser(): Observable<any> {
return this.accountService.create(this.modelForm.value).pipe(
finalize(() => (this.isInProgress = false))
);
}
To handle the response
handleResponse(): any {
return {
next: res => {
this.notificationService.showSuccess('User has been created successfully.');
this._router.navigate(['settings/user']);
},
error: err => {
this.notificationService.showError('Something went wrong, Try again later.');
this.isInProgress = false;
}
complete: () => this.isInProgress = false;
};
}
Check out the Demo
If you encounter issues accessing the button, you can move the ngOnInit Code to AfterViewInit
Let me know if there are any errors as I have not fully tested your code.
ngAfterViewInit(): void {
fromEvent(this.button.nativeElement, 'click')
.pipe(
tap(x => console.log('clicked.')),
exhaustMap(ev => {
console.log(`processing API call`);
return this.createUser();
})
)
.pipe(tap(x => console.log('Api call completed....')))
.subscribe(this.handleResponse());
}