[英]Returning an Observable<boolean> from canActivate and redirect on false
I have a reactive form in my Angular App.我的 Angular 应用程序中有一个反应形式。 Every time on form value change I am storing a Boolean in a BehaviorSubject in my common service.
每次更改表单值时,我都会将 Boolean 存储在我常用服务的 BehaviorSubject 中。
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.我创建了一个路由守卫,我想根据 BehaviorSubject 的值停止导航,如果是真的我想停止导航。 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.我同意 Aluan Haddad 的评论。 The canDeactive Guard from Angular should do exactly what you want to achieve.
Angular 的 canDeactive Guard 应该完全符合您的要求。 Have a look: Angular CanDeactivate
看看: Angular CanDeactivate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.