问题描述
我正在尝试在Angular 6应用中实现延迟加载,我所有的http调用都在FeatureModule
中进行(延迟加载),但是我仍然必须在AppModule
中添加HttpClientModule
而不是在FeatureModule
.真的不明白为什么.另外,当我在FeatureModule
中添加拦截器时,它们没有拦截任何请求.我只需要在AppModule
中添加它(我想是因为HttpClientModule
在AppModule
中).
I am trying to implement lazy loading in my Angular 6 app, all of my http calls are made in the FeatureModule
(lazy loaded), but still I have to add HttpClientModule
in my AppModule
and not in FeatureModule
. Didn't really understand why.Also, when I added interceptors in my FeatureModule
, they didn't intercept any request. I have to add it in the AppModule
only (I guess, it is because HttpClientModule
is in AppModule
).
我想了解为什么会这样吗?为什么我们不能只在FeatureModule
中有HttpClientModule
和HTTP_INTERCEPTORS
而在没有进行任何http
调用的AppModule
中没有?
I want to understand why this is the case?? Why can't we have HttpClientModule
and HTTP_INTERCEPTORS
only in the FeatureModule
and not in AppModule
where I am not making any http
calls?
推荐答案
要回答此问题.
仅一次在根级别添加HttpClientModule
.没有其他模块,无论它们如何从lazy
或eager
导入,即使它们是从库中导入的也是如此.确保它没有导入HttpClientModule
Only add HttpClientModule
at once place at the root level. No other modules regardless of how they are imported lazy
or eager
even if it is from a library. Ensure that it is not importing HttpClientModule
但是,您可以跨模块使用HTTP_INTERCEPTORS提供程序,而不会出现问题.
You can however use HTTP_INTERCEPTORS providers across modules without an issue.
在跨模块导入HttpClientModule
并将其重新导入到另一个模块时,它将有效地重置该模块的HTTP_INTERCEPTORS提供程序.这是预期的行为.如果您需要有关讨论的更多信息,可以查看: https://github.com/angular/angular/issues/20575
When you import HttpClientModule
across modules and then re import that into another module it effectively resets the providers for HTTP_INTERCEPTORS for that module.This is an intended behaviour. If you need more information about the discussion you can check: https://github.com/angular/angular/issues/20575
这篇关于仅在AppModule中使用HTTP_INTERCEPTORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!