HTTP_INTERCEPTORS 仅在 AppModule 中
HTTP_INTERCEPTORS only in AppModule
我正在尝试在我的 Angular 6 应用程序中实现延迟加载,我所有的 http 调用都是在 FeatureModule
中进行的(延迟加载),但我仍然必须添加 HttpClientModule
在我的 AppModule
而不是 FeatureModule
。真的不明白为什么。
此外,当我在 FeatureModule
中添加拦截器时,它们没有拦截任何请求。我必须将它添加到 AppModule
中(我猜,这是因为 HttpClientModule
在 AppModule
中)。
我想明白为什么会这样??为什么我们不能只在 FeatureModule
中使用 HttpClientModule
和 HTTP_INTERCEPTORS
而不是在 AppModule
中我不进行任何 http
调用?
回答这个问题。
在根级别一次只添加 HttpClientModule
个位置。没有其他模块,无论它们是如何导入 lazy
或 eager
即使它来自库。确保它没有导入 HttpClientModule
但是,您可以跨模块使用 HTTP_INTERCEPTORS 提供程序而不会出现问题。
当您跨模块导入 HttpClientModule
然后将其重新导入另一个模块时,它会有效地重置该模块的 HTTP_INTERCEPTORS 的提供程序。
这是预期的行为。如果您需要有关讨论的更多信息,可以查看:https://github.com/angular/angular/issues/20575
最后一个答案很好,最佳实践说你只需要一个 HtppclientModule 最好将它放入 core.module.ts 并将 core.module.ts 导入 app.module.ts.
core.module.ts
enter image description here
app.module.ts
enter image description here
我正在尝试在我的 Angular 6 应用程序中实现延迟加载,我所有的 http 调用都是在 FeatureModule
中进行的(延迟加载),但我仍然必须添加 HttpClientModule
在我的 AppModule
而不是 FeatureModule
。真的不明白为什么。
此外,当我在 FeatureModule
中添加拦截器时,它们没有拦截任何请求。我必须将它添加到 AppModule
中(我猜,这是因为 HttpClientModule
在 AppModule
中)。
我想明白为什么会这样??为什么我们不能只在 FeatureModule
中使用 HttpClientModule
和 HTTP_INTERCEPTORS
而不是在 AppModule
中我不进行任何 http
调用?
回答这个问题。
在根级别一次只添加 HttpClientModule
个位置。没有其他模块,无论它们是如何导入 lazy
或 eager
即使它来自库。确保它没有导入 HttpClientModule
但是,您可以跨模块使用 HTTP_INTERCEPTORS 提供程序而不会出现问题。
当您跨模块导入 HttpClientModule
然后将其重新导入另一个模块时,它会有效地重置该模块的 HTTP_INTERCEPTORS 的提供程序。
这是预期的行为。如果您需要有关讨论的更多信息,可以查看:https://github.com/angular/angular/issues/20575
最后一个答案很好,最佳实践说你只需要一个 HtppclientModule 最好将它放入 core.module.ts 并将 core.module.ts 导入 app.module.ts.
core.module.ts
enter image description here
app.module.ts
enter image description here