Angular7: Global Guard - CanDeactivate 接口
Angular7: Global Guard - CanDeactivate interface
我是 Angular 的新手,未能找到我正在搜索的答案。
我现在面临的问题是,当我切换到另一条路线时,所有的全局错误信息都没有消失。
我尝试使用 CanDeactivate 接口解决这个问题。
这是我的 canDeactivate 方法:
canDeactivate(): Observable<boolean> {
console.log('delete test');
this.globalMessageService.remove(GlobalMessageType.MSG_TYPE_ERROR);
return of(true);
}
此方法是在名为 cms-page.guard.ts 的服务中创建的,通过在特定页面中使用它,它似乎工作得很好。例如,如果我在 "Courses" 页面中使用它:
const routes: Routes = [
{
path: 'courses',
canActivate: [CmsPageGuards],
canDeactivate: [CmsPageGuards],
data: { pageLabel: 'courses' },
component: CoursesPageComponent
}
];
基本上,我所做的是在特定页面上应用 canDeactivate 方法。
我想知道是否可以创建一个全局应用 canDeactivate 方法的 Guard,以便当您更改到另一条路线时它适用于所有页面?
我认为你的目标是处理全局错误。您不需要为此使用 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。
希望对你有帮助!
我是 Angular 的新手,未能找到我正在搜索的答案。
我现在面临的问题是,当我切换到另一条路线时,所有的全局错误信息都没有消失。
我尝试使用 CanDeactivate 接口解决这个问题。 这是我的 canDeactivate 方法:
canDeactivate(): Observable<boolean> {
console.log('delete test');
this.globalMessageService.remove(GlobalMessageType.MSG_TYPE_ERROR);
return of(true);
}
此方法是在名为 cms-page.guard.ts 的服务中创建的,通过在特定页面中使用它,它似乎工作得很好。例如,如果我在 "Courses" 页面中使用它:
const routes: Routes = [
{
path: 'courses',
canActivate: [CmsPageGuards],
canDeactivate: [CmsPageGuards],
data: { pageLabel: 'courses' },
component: CoursesPageComponent
}
];
基本上,我所做的是在特定页面上应用 canDeactivate 方法。 我想知道是否可以创建一个全局应用 canDeactivate 方法的 Guard,以便当您更改到另一条路线时它适用于所有页面?
我认为你的目标是处理全局错误。您不需要为此使用 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。 希望对你有帮助!