简体   繁体   中英

Returning an Observable<boolean> from canActivate and redirect on false

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
        }
      })
    )
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM