我对Angular非常陌生,并没有成功地找到我正在寻找的答案。
我现在面临的问题是,当我切换到另一个路由时,所有的全局错误消息都不会消失。
我试图通过使用CanDeactivate接口来解决这个问题。这是我的canDeactivate方法:
canDeactivate(): Observable<boolean> {
console.log('delete test');
this.globalMessageService.remove(GlobalMessageType.MSG_TYPE_ERROR);
return of(true);
}
此方法是在名为cms-page.guard.ts的服务中创建的,通过在特定页面中使用此方法,它似乎工作得很好。如果我在“课程”页面中使用这个示例:
const routes: Routes = [
{
path: 'courses',
canActivate: [CmsPageGuards],
canDeactivate: [CmsPageGuards],
data: { pageLabel: 'courses' },
component: CoursesPageComponent
}
];
基本上,我所做的就是在特定页面上应用canDeactivate方法。我想知道是否有可能创建一个全局应用canDeactivate方法的卫士,这样当您切换到另一个路由时,它就可以在所有页面上工作。
发布于 2019-06-18 19:23:12
我认为您的目标是处理全局错误。您不需要使用canDeactivateGuard来实现同样的目的。您可以通过ErrorHandler接口实现这一点。
import { ErrorHandler, Injectable} from '@angular/core';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor() { }
handleError(error) { //override handleError method
//handle all errors here
console.log('error')
// IMPORTANT: Rethrow the error otherwise it gets swallowed
throw error;
}
}现在我们只需要告诉angular使用GlobalErrorHandler而不是它的默认设置
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent],
providers: [
{
provide: ErrorHandler,
useClass: GlobalErrorHandler
}
]
})
export class AppModule { }对于所有在app.module.ts中声明的组件,将使用GlobalErrorHandler。希望能对你有所帮助!
https://stackoverflow.com/questions/56644664
复制相似问题