In my Angular application, I have a reactive form that triggers a change in a Boolean value stored in a BehaviorSubject within a common service whenever the form value is updated.
I have implemented a route guard to prevent navigation based on the current value of the BehaviorSubject. If the value is true, navigation should be halted. However, my initial implementation does not seem to be working, indicating a possible issue with my subscription.
Component
onCreateGroupFormValueChange() {
const initialValue = this.createGroupForm.value;
this.createGroupForm.valueChanges.subscribe((value) => {
this.hasUnsavedData = Object.keys(initialValue).some(
(key) => this.createGroupForm.value[key] != initialValue[key]
);
this._helperService.onFormValueChange(this.hasUnsavedData);
});
}
Service
private _unsaveDataSource = new BehaviorSubject<boolean>(false);
public unsavedForm$ = this._unsaveDataSource.asObservable();
onFormValueChange(hasData : boolean){
this._unsaveDataSource.next(hasData);
}
Guard
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
return this._helperService.unsavedForm$.pipe(
map(e => {
if(e){
return false
}else{
return true
}
})
)
}