如何仅为子模块导入 Angular HTTP 拦截器
How to import Angular HTTP interceptor only for Child module
我在 AppModule 中导入了 HttpClientModule。
import { HttpClientModule } from '@angular/common/http';
export const AppRoutes: Routes = [
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{
path: 'account',
loadChildren: './auth/auth.module#AuthModule'
},
{
path: 'dashboard',
loadChildren: './content/content.module#ContentModule'
}
];
一旦我启动站点,它将重定向到我添加了 http 拦截器的仪表板模块(延迟加载模块)。
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpInterceptorService } from '../services/http-interceptor.service';
@NgModule({
providers : [
{ provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }
]
})
但它不起作用。谁能帮帮我?
Http 拦截器只是一个服务,在任何模块上注入它都没有任何区别 - 只需在 AppModule
中做同样的事情,这将帮助你工作 - 如果你遇到同样的问题你可以尝试在你的共享模块上像下面这样注入
实现这一点的常见模式不是在 @NgModule
声明中直接公开提供程序,而是在像这样的静态 forRoot 函数中公开提供程序:
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }
]
};
}
}
然后您可以像 SharedModule.forRoot()
一样在 AppModule
上导入您的 SharedModule
希望这有效 - 编码愉快
这个问题很老了,但对于未来在这个线程上遇到问题并扩展已接受的答案的人来说:
Angular 应该在注入 Http 客户端之前注册拦截器
Because interceptors are (optional) dependencies of the HttpClient service, you must provide them in the same injector (or a parent of the injector) that provides HttpClient. Interceptors provided after DI creates the HttpClient are ignored.
因此,应该在 HttpClientModule
导入之前提供任何拦截器,自动注入 HttpClient
服务(副作用)
我在 AppModule 中导入了 HttpClientModule。
import { HttpClientModule } from '@angular/common/http';
export const AppRoutes: Routes = [
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{
path: 'account',
loadChildren: './auth/auth.module#AuthModule'
},
{
path: 'dashboard',
loadChildren: './content/content.module#ContentModule'
}
];
一旦我启动站点,它将重定向到我添加了 http 拦截器的仪表板模块(延迟加载模块)。
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpInterceptorService } from '../services/http-interceptor.service';
@NgModule({
providers : [
{ provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }
]
})
但它不起作用。谁能帮帮我?
Http 拦截器只是一个服务,在任何模块上注入它都没有任何区别 - 只需在 AppModule
中做同样的事情,这将帮助你工作 - 如果你遇到同样的问题你可以尝试在你的共享模块上像下面这样注入
实现这一点的常见模式不是在 @NgModule
声明中直接公开提供程序,而是在像这样的静态 forRoot 函数中公开提供程序:
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }
]
};
}
}
然后您可以像 SharedModule.forRoot()
AppModule
上导入您的 SharedModule
希望这有效 - 编码愉快
这个问题很老了,但对于未来在这个线程上遇到问题并扩展已接受的答案的人来说:
Angular 应该在注入 Http 客户端之前注册拦截器
Because interceptors are (optional) dependencies of the HttpClient service, you must provide them in the same injector (or a parent of the injector) that provides HttpClient. Interceptors provided after DI creates the HttpClient are ignored.
因此,应该在 HttpClientModule
导入之前提供任何拦截器,自动注入 HttpClient
服务(副作用)