Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

angular - 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
        }
      })
    )
  }
question from:https://stackoverflow.com/questions/65661518/returning-an-observableboolean-from-canactivate-and-redirect-on-false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...