Reputation: 955
I have a reactive form in my Angular App. Every time on form value change I am storing a Boolean in a BehaviorSubject in my common service.
I have created a route guard and I want stop the navigation based on the BehaviorSubject's value, if it is true I want to stop the navigation. I have tried this approach below but I it not working. Maybe I am not subscribing properly.
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
}
})
)
}
Upvotes: 0
Views: 187
Reputation: 90
I agree with Aluan Haddad's comment. The canDeactive Guard from Angular should do exactly what you want to achieve. Have a look: Angular CanDeactivate
Upvotes: 2