2016-04-21 27 views
6

İstisnai bir durum oluşursa (yalnızca denemek) kullanıcıyı özel bir hata sayfasına götürmesi gereken özel bir özel durum işleyicim var.Açısal 2 Özel Hata Giderme ve Yönlendirici

Enjektör kullanarak yönlendiricinin örneğini almaya çalışıyorum. Bunu yapmanın nedeni, enjektörün mevcut yönlendirici örneğini vereceğine ve onu kullanacağına inanıyorum.

Bunun neden çalışmadığı veya bunun nasıl gerçekleştirilebileceği hakkında herhangi bir fikrin var mı?

Sen

@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"]); 
    } 

} 

Cevap :) Teşekkür - 2.0.0-beta.17 test Teşekkür 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 
için
 
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"]); 
     } 
    } 

} 
+0

buldun Bu soruna bir çözüm? – Scipion

+0

Merhaba, soruyu cevapla güncelledik. :) – ssujan728

cevap

1

bu sınıf bağımlılık enjeksiyon gerçekleşir beri bu şekilde Özelliğinizi uygulayacağını: En kolu bu şekilde

@Injectable() 
export class AppExceptionHandler extends ExceptionHandler { 
    constructor(private router:Router) { 
    super(null, null); 
    } 

    call(exception:any, stackTrace?:any, reason?:string):void { 
    console.log('call...') 

    this.router.navigate(['CustomErrorPage']); 
    } 
} 

ve kayıt:

bootstrap(MyApp, [ 
    provide(ExceptionHandler, {useClass: AppExceptionHandler}) 
]); 
+0

önerisi için teşekkürler Başlangıçta bu şekilde yapıldı. Hala bana problemler verdi. Hata mesajından, AppExceptionHandler'ın Router'dan önce başlatılmış gibi göründüğü için enjekte edilemez. i enjektörüne swithced neden ' bile hiç bir çalışma, yani;: I ([{AppExceptionHandler useClass}) (ExceptionHandler, ROUTER_PROVIDERS, temin] Uygulamam) bu çok ' ön yükleme çalıştı. – ssujan728