我目前正在尝试对我的 Angular 应用程序实施 CanDeactivate Guard,该应用程序已经具有 HTTP 拦截器来解析身份验证。但是添加 CanDeactivate 防护会引发错误,如下所述。
我已经在 AppModule 的 providers 数组中注册了实现 CanDeactivate 接口的类。我已经在路由的 canDeactivate 属性中注册了实现 CanDeactivate 接口的类。
实现 CanDeactivate 接口的类:
export interface CanComponentDeactivate {
canComponentDeactivate(): boolean;
}
@Injectable({providedIn: 'root'})
export class AppRegisterDeactivateGuard implements CanDeactivate<AppRegisterComponent> {
canDeactivate(
component: AppRegisterComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean {
return component.isDeactivated;
}
}
应用了 Deactivate 防护的组件:
@Component({
selector: 'app-app-register',
templateUrl: './app-register.component.html',
styleUrls: ['./app-register.component.css']
})
export class AppRegisterComponent implements OnInit, CanComponentDeactivate {
isDeactivated = false;
@ViewChild('registrationForm') registForm: NgForm;
.
.
canComponentDeactivate() {
if (this.registForm.dirty) {
this.isDeactivated = confirm('You have modified changes in the form. \nDo you still want to navigate away ? ');
}
return this.isDeactivated;
}
}
该端点的路由定义:
...
{ path: 'register', component: AppRegisterComponent, canDeactivate: ['AppRegisterDeactivateGuard'] },
Module 中的 Providers 数组:
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: AppAuthInterceptService,
multi: true
}, AppRegisterDeactivateGuard],
bootstrap: [AppComponent]
错误
StaticInjectorError(Platform: core)[AppRegisterDeactivateGuard]:
NullInjectorError: No provider for AppRegisterDeactivateGuard!
Error: StaticInjectorError(AppModule)[AppRegisterDeactivateGuard]:
StaticInjectorError(Platform: core)[AppRegisterDeactivateGuard]:
NullInjectorError: No provider for AppRegisterDeactivateGuard!
at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (core.js:8896)
at resolveToken (core.js:9141)
at tryResolveToken (core.js:9085)
at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:8982)
at resolveToken (core.js:9141)
at tryResolveToken (core.js:9085)
at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (core.js:8982)
at resolveNgModuleDep (core.js:21218)
at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (core.js:21907)
at getToken (router.js:2865)
at resolvePromise (zone.js:831)
at resolvePromise (zone.js:788)
at zone.js:892
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Object.onInvokeTask (core.js:17290)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
at drainMicroTaskQueue (zone.js:601)
at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:502)
at invokeTask (zone.js:1744)