由于您可以向守卫中的CanDeactivate()
返回Observable<boolean>
,因此您可能不需要下一个路由的目标URL。
当我们检查守卫时,我们触发组件中更改的检查,并将过滤后的 Observable 返回给守卫。(仅将其过滤为“true”值-否则我们将无法继续导航到所需的路由!)
当我们的检查通过时,我们可以导航-如果不行,则不能。
因此,我们可能想向用户显示两个按钮。 一个用于跳过保存并导航(doNotSaveAndNavigate()
),另一个用于保存并继续导航(doSaveAndNavigate()
)...或任何其他帮助来指导他或她..
some.component.ts
import { Component } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'selector',
templateUrl: 'some.component.html'
})
export class SomeComponent {
youMayNavigateSource = new BehaviorSubject<boolean>(false);
youMayNavigate$: Observable<boolean> = this.youMayNavigateSource.asObservable();
checkForUnsavedChanges(): void {
let hasSaved: boolean = false;
this.youMayNavigateSource.next(hasSaved);
}
canDeactivate(): Observable<boolean> {
this.checkForUnsavedChanges();
return this.youMayNavigate$.filter(el => el);
}
allowNavigation(): void {
this.youMayNavigateSource.next(true);
}
doNotSaveAndNavigate(): void {
this.allowNavigation();
}
doSaveAndNavigate(): void {
this.doSave();
this.allowNavigation();
}
doSave(): void {
}
}
can-deactivate-guard.service.ts
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { SomeComponent } from './some.component';
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<SomeComponent > {
canDeactivate(component: SomeComponent ) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
我猜你知道如何为路由设置CanDeactivate,但为了完整起见,你可以在官方文档中找到一个使用示例。
提示:如果您只想在CanDeactivate()
失败时获取URL,请订阅router.events
并过滤NavigationCancel
事件,如下所示:
this.router.events
.filter(event => event instanceof NavigationCancel)
.subscribe(el => console.log('Requested URL:', el.url));
您可能需要导入:
import { Router, NavigationCancel } from '@angular/router';
import 'rxjs/add/operator/filter';
并将
router
添加到您的构造函数中:
constructor(private router: Router) { }