我一直在尝试编写一个canDeactivate防护来检查可观察流中的保存状态并相应地工作.
我的服务就是这样
import { Injectable } from '@angular/core'; import { ReplaySubject } from 'rxjs/ReplaySubject'; import { Observable } from 'rxjs/Observable'; @Injectable() export class EditModelService { private savingModelDataSource = new ReplaySubject<boolean>(); savingModelData$= this.savingModelDataSource.asObservable(); public setSavingModelData(state: boolean) { this.savingModelDataSource.next(state); } }
我的后卫就像
import { Injectable } from '@angular/core'; import { CanDeactivate,ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { EditModelService } from './edit-model.service'; @Injectable() export class EditModelCanDeactivateGuardGuard { private savingState: boolean; constructor( private editModelService: EditModelService ) { } CanDeactivate( currentRoute: ActivatedRouteSnapshot,currentState: RouterStateSnapshot ): Observable<boolean> | Promise<boolean> | boolean { this.editModelService.savingModelData$.subscribe(saving => { this.savingState = saving; }); if (this.savingState) { return this.editModelService.savingModelData$.first(); } else { return this.editModelService.savingModelData$.first(); } } }
基本上,它从服务获取savingState的值并根据状态返回,因此路由器的canDeactivate属性接收一个布尔值.
由于守护中的this.savingState值始终被订阅,因此我认为条件不存在问题.
通过一些搜索,我遇到了这个answer,并尝试将守卫代码作为
return this.editModelService.savingModelData$.first();
当然,我在这里导入了first()作为import’rxjs / add / operator / first’;.
它返回一个来自守卫的观察者只是为了看它是否正常工作或者是否与我返回的方式有关.但是,在这两种情况下,我都会收到错误,如下图所示.
我在导入路由器配置的模块中提供了路由器防护.这也是提供服务的地方.
我在这做错了什么?我是新手使用路由器防护(尤其是canDeactivate with observable),任何帮助表示赞赏.
您的Guard Service必须实现功能以完全实现CanActivate或CanDeactivate接口.尝试改变为
从
@Injectable() export class EditModelCanDeactivateGuardGuard {
至
@Injectable() export class EditModelCanDeactivateGuardGuard implements CanActivate,CanDeactivate<boolean>{
您的CanDeactivate也应更改为canDeactivate
canDeactivate() { }
尝试解决方案后更新:
另外,改变
从
canDeactivate( currentRoute: ActivatedRouteSnapshot,currentState: RouterStateSnapshot ): Observable<boolean> | Promise<boolean> | boolean ...
至
canDeactivate(): Observable<boolean> | Promise<boolean> | boolean...