Tôi có trình xử lý ngoại lệ tùy chỉnh được cho là đưa người dùng đến trang lỗi tùy chỉnh nếu có bất kỳ ngoại lệ nào xảy ra (chỉ cần dùng thử).Góc 2 Xử lý lỗi tùy chỉnh và Bộ định tuyến
Tôi đang cố gắng lấy phiên bản của bộ định tuyến bằng cách sử dụng Injector. Lý do để làm điều này, tôi tin rằng các vòi phun sẽ cung cấp cho các ví dụ router hiện có và sử dụng nó tôi sẽ có thể định tuyến người dùng.
Bất kỳ ý tưởng nào tại sao tính năng này không hoạt động hoặc cách thức này có thể đạt được?
cảm ơn :)
@Injectable()
export class AppExceptionHandler extends ExceptionHandler{
constructor(){
super(null, null);
}
call(exception:any, stackTrace?:any, reason?:string):void {
console.log('call...')
var providers = Injector.resolve([ROUTER_PROVIDERS]);
var injector = Injector.fromResolvedProviders(providers);
// this is causing issue, not sure it is the correct way
let router : Router = injector.get(Router);
// not executed
console.log(router)
// not executed
console.log('done...')
router.navigate(["CustomErrorPage"]);
}
}
trả lời - thử nghiệm trong 2.0.0-beta.17 Nhờ Druxtan
1. Created a file app.injector.ts inside the app folder (app/app.injector.ts)
let appInjectorRef;
export const appInjector = (injector?) => {
if (!injector) {
return appInjectorRef;
}
appInjectorRef = injector;
return appInjectorRef;
};
2. Added to the bootstrap in the main.ts
bootstrap(AppComponent,[ROUTER_PROVIDERS, HTTP_PROVIDERS,provide(ExceptionHandler,{useClass : AppExceptionHandler})])
.then((appRef) => appInjector(appRef.injector));
3. In the AppExceptionHandler, retrieved the Router instance as shown below
export class AppExceptionHandler {
call(exception:any, stackTrace?:any, reason?:string):void {
let injectorApp = appInjector();
let router = injectorApp.get(Router);
let localStorageService = injectorApp.get(LocalStorageService);
if(exception.message === '-1'){
localStorageService.clear();
router.navigate(["Login"]);
}
}
}
Bạn đã tìm thấy một giải pháp cho vấn đề này? – Scipion
hi đã cập nhật câu hỏi với câu trả lời. :) – ssujan728