插入Interceptor后未定义Angular 6服务 [英] Angular 6 Service is undefined after injecting in Interceptor
问题描述
我找不到将 AuthService 注入 ErrorHandlerInterceptor 内的任何方法. 注入后返回一个" undefined "对象,或者引发错误.
I can't find any way to inject my AuthService inside ErrorHandlerInterceptor. It returns me either an "undefined" object after injection, or it throws an error.
这是我的 ErrorHandlerInterceptor :
This is my ErrorHandlerInterceptor:
import { Injectable } from '@angular/core';
import { AuthService } from '@app/auth.service';
import { StorageService } from '@app/storage.service';
@Injectable({
providedIn: 'root'
})
export class ErrorHandlerInterceptor implements HttpInterceptor {
constructor(private authService: AuthService, private storageService: StorageService) {
console.log(this.authService); // undefined
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(error => this.errorHandler(error)));
}
// Customize the default error handler here if needed
private errorHandler(response: HttpErrorResponse): Observable<HttpEvent<any>>
{
// ... Various code
}
}
这是我的 AuthService :
And this is my AuthService:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { StorageService } from './storage.service';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private _http: HttpClient,
private storageService: StorageService,
private router: Router) { }
}
我试图在core.module.ts
提供程序中列出该服务,但抛出错误:
I tried to list the service in the core.module.ts
providers, but errors are thrown:
ERROR RangeError: Maximum call stack size exceeded
at setCurrentInjector (core.js:1382)
at resolveNgModuleDep (core.js:8333)
at _createClass (core.js:8425)
at _createProviderInstance (core.js:8393)
at resolveNgModuleDep (core.js:8356)
at _createClass (core.js:8425)
at _createProviderInstance (core.js:8393)
at resolveNgModuleDep (core.js:8356)
at _createClass (core.js:8425)
at _createProviderInstance (core.js:8393)
请注意,我正在使用由ngx-rocket-generator
创建的框架ngx-rocket
.
Note that I am using the framework ngx-rocket
, created by ngx-rocket-generator
.
如何解决此问题?有什么建议吗?
How can I do to fix this issue? Any advices?
更新1-CORE.MODULE.TS
这是core.module.ts文件.
Here is the core.module.ts file.
import { NgModule, Optional, SkipSelf } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HTTP_INTERCEPTORS, HttpClient, HttpClientModule } from '@angular/common/http';
import { RouteReuseStrategy, RouterModule } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ShellComponent } from './shell/shell.component';
import { HeaderComponent } from './shell/header/header.component';
import { RouteReusableStrategy } from './route-reusable-strategy';
import { AuthenticationService } from './authentication/authentication.service';
import { AuthenticationGuard } from './authentication/authentication.guard';
import { I18nService } from './i18n.service';
import { HttpService } from './http/http.service';
import { HttpCacheService } from './http/http-cache.service';
import { ApiPrefixInterceptor } from './http/api-prefix.interceptor';
import { ErrorHandlerInterceptor } from './http/error-handler.interceptor';
import { CacheInterceptor } from './http/cache.interceptor';
import { TokenInterceptor } from './http/token.interceptor';
import { StorageService } from '@app/storage.service';
import { AuthService } from '@app/auth.service';
@NgModule({
imports: [
CommonModule,
HttpClientModule,
TranslateModule,
NgbModule,
RouterModule
],
declarations: [
HeaderComponent,
ShellComponent
],
providers: [
AuthenticationService,
AuthenticationGuard,
I18nService,
HttpCacheService,
ApiPrefixInterceptor,
ErrorHandlerInterceptor,
CacheInterceptor,
TokenInterceptor,
{
provide: HttpClient,
useClass: HttpService
},
{
provide: RouteReuseStrategy,
useClass: RouteReusableStrategy
}
]
})
export class CoreModule {
constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
// Import guard
if (parentModule) {
throw new Error(`${parentModule} has already been loaded. Import Core module in the AppModule only.`);
}
}
}
推荐答案
最后,我解决了这个问题. 在错误处理程序中,不能通过构造函数注入依赖项. 要解决它,您需要执行以下操作:
Finally, I solved the problem. In the error handler, the dependencies cannot be injected through the constructor. To solve it, you need to do this:
首先,从@angular/core
和您的服务导入喷油器:
First, import the Injector from @angular/core
and your service:
import { Injector } from '@angular/core';
import { AuthService } from '@app/auth.service';
然后,您必须将其注入到构造函数中:
Then, you have to inject it in the constructor:
constructor(private modalService: NgbModal, private injector: Injector) { }
然后您必须实例化服务并像这样使用它:
And then you have to instantiate your service and use it like this:
const authService = this.injector.get(AuthService);
authService.logout();
代码将与此类似:
import { Injector } from '@angular/core';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class ErrorHandlerInterceptor implements HttpInterceptor {
private authService: AuthService;
constructor(private modalService: NgbModal, private router: Router, private injector: Injector) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(error => this.errorHandler(error)));
}
// Customize the default error handler here if needed
private errorHandler(response: HttpErrorResponse): Observable<HttpEvent<any>> {
this.authService = this.injector.get(AuthService);
... Other code ...
}
希望这个答案对您有所帮助!
Hope you have been helped by this answer!
这篇关于插入Interceptor后未定义Angular 6服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!