[英]Angular - Use Injector for Router in Service
I try to implement an error service which need to use the Angular Router methods in this class.我尝试实现一个错误服务,该服务需要使用此类中的 Angular Router 方法。 And all I can found is to insert the Router class into my service by using Injector method of Angular.
我所能找到的就是使用 Angular 的 Injector 方法将 Router 类插入到我的服务中。
So, I do grab the Injector object with dependency injection in my constructor of my serice class:所以,我确实在我的服务类的构造函数中使用依赖注入获取了 Injector 对象:
Import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class RequestErrorHandlerService implements ErrorHandler {
private _router: any
constructor(
private injector: Injector
) {}
handleError(error) {
const router = this.injector.get(Router);
...
router.navigate(['/login']);
}
}
And I try to use injector.get() for to get the Router object.我尝试使用 injector.get() 来获取 Router 对象。 But all I get is an error
但我得到的只是一个错误
Uncaught TypeError: this.injector.get is not a function
未捕获的类型错误:this.injector.get 不是函数
So, I think I forgot something.所以,我想我忘记了一些事情。 But didn´t get the problem.
但没有得到问题。 Why does this not works?
为什么这不起作用?
Do have somebody a tip for me, or an link to a tutorial which realy works with Angular Version 8 or higher?有没有人给我一个提示,或者一个真正适用于 Angular 8 或更高版本的教程的链接?
Thanks.谢谢。
Recently faced same issue, and had similar code that you had mentioned.最近遇到了同样的问题,并且有你提到的类似代码。
Check if you have mentioned the ErrorHandler
in app module providers like below:检查您是否在应用模块提供程序中提到了
ErrorHandler
,如下所示:
{
provide: ErrorHandler,
useClass: RequestErrorHandlerService
}
and not like below (Previously, in app module providers, when I had mentioned ErrorHandler as given below, it didn't work for me)而不是像下面(此前,在应用模块供应商,当我提到的ErrorHandler如下面给出的,它并没有对我的工作)
{
provide: ErrorHandler,
useClass: RequestErrorHandlerService,
deps: [APP_INITIALIZER]
}
Anyways, below is some code snippets that worked for me, which might be useful.无论如何,下面是一些对我有用的代码片段,它们可能有用。
app-error-handler.ts
: app-error-handler.ts
:
@Injectable()
export class AppErrorHandler implements ErrorHandler {
constructor(private injector: Injector) {}
handleError(error: Error) {
console.log('Client side - ' + error.message);
const router = this.injector.get(Router);
router.navigate(['login']);
}
}
app.module.ts
: app.module.ts
:
@NgModule({
// ...
providers: [
{
provide: ErrorHandler,
useClass: AppErrorHandler
}
// ...
],
})
export class AppModule { }
You should be able to simply inject the Router via the constructor:您应该能够通过构造函数简单地注入路由器:
export class RequestErrorHandlerService implements ErrorHandler {
constructor(
private router: Router
) {}
handleError(error) {
this.router.navigate(['/login']);
}
}
Why not just like this ?为什么不只是这样?
import { Router } from '@angular/router';
constructor(private router: router) {}
handleError(error) {
this.router.navigate(['/login']);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.