gpt4 book ai didi

angular - 无法在 CanDeactivate 路由器防护中获取下一个状态(下一个 url)

转载 作者:行者123 更新时间:2023-12-05 01:01:01 27 4
gpt4 key购买 nike

我为 CanDeactivate 功能添加了以下路由器保护,以验证未保存的更改,这对我来说工作正常

导出接口(interface) CanComponentDeactivate { canDeactivate: () => 可观察 | promise | bool 值; }

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
constructor( private eventService: EventsService) { }
canDeactivate(component: CanComponentDeactivate, route?: ActivatedRouteSnapshot,
currentState?: RouterStateSnapshot,
nextState?: string) {
let sub = new Subject();
if (BaseApiService.callStack.length || UnsavedData.isThereUnSavedData) {
this.eventService.triggerEvent(CONST.SHOW_DATA_LOSS_MODAL, {
showDataLossModal: true,
sub : sub
});
}
return BaseApiService.callStack.length || UnsavedData.isThereUnSavedData ? false : true;
}
}

但是当我检测到是否有任何未保存的更改时,我会显示一个带有"is"和“否”按钮的对话框。

如果用户单击"is",我必须清除未保存的更改并重定向到用户单击的 URL。为此,我必须检查用户想要在 CanDeactivate 函数上重定向的 URL。

nextState?: string 但是每次我得到这个 undefined。

如果我做了任何更改,请纠正我。

最佳答案

你需要使用,

nextState?:RouterStateSnapshot

下面是接口(interface)定义,

interface CanDeactivate<T> { 
canDeactivate(component: T,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean
}

检查定义here .

更新

查看下面的完整示例,

@Component({
selector: 'my-app',
template: `<h1>Hello {{name}}</h1>
<hr />
<a routerLink="/home" >Home</a>
<a routerLink="/other" >Other</a>
<hr />
<router-outlet></router-outlet>
`
})
class AppComponent { name = 'Angular'; }

@Component({
template: `<h1>Home</h1>

<a routerLink="/other" >Go to Other from Home</a>
`
})
class HomeComponent {
}

@Component({
template: `<h1>Other</h1>
`
})
class OtherComponent {
}

@Injectable()
class CanDeactivateHome implements CanDeactivate<HomeComponent> {
canDeactivate(
component: HomeComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean {

console.log(component);
console.log(currentRoute);
console.log(currentState);
console.log(nextState);

return true;
}
}

const appRoutes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent, canDeactivate: [CanDeactivateHome] },
{ path: 'other', component: OtherComponent }
];

@NgModule({
imports: [ BrowserModule, RouterModule.forRoot(appRoutes)],
declarations: [ AppComponent, HomeComponent, OtherComponent ],
providers: [CanDeactivateHome],
bootstrap: [ AppComponent ]
})
export class AppModule { }

查看 Plunker!!

关于angular - 无法在 CanDeactivate 路由器防护中获取下一个状态(下一个 url),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46691432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com