Sharikov Vladislav
Sharikov Vladislav

Reputation: 7279

How to add http interceptor only in one specific NgModule (without lazy-loading)?

I need to implement some feature. I want to provide some http interceptor in modules A and B. I want each http request from module A to be sent with some header like 'zone: a-feature'. Any request from module B must be sent with header like 'zone: b-feature'.

I am trying to implement this using custom http interceptors.

Here is what I tried: https://stackblitz.com/edit/angular-j3siwz

  1. I created 2 modules with 2 components A & B
  2. Each component send request
  3. Each module has custom TOKEN provider
  4. In http interceptor I want to inject token provider.

The problem is how angular works :) Looks like, by design all dependencies are provided in some "Root module". So when I provide "another" token in B module I just rewrite this token in root module injector.

So in my example in both requests I get 'a-feature' message in console log. Interceptor is created only one time with 1 token value (article below describes exactly why behavior is so).

Looks like angular docs clearly says this: https://angular.io/guide/dependency-injection

Also I found and red this perfect article: https://blog.angularindepth.com/angular-dependency-injection-and-tree-shakeable-tokens-4588a8f70d5d.

Looks like, lazy loaded modules work differently. But in my case I don't have lazy loading so I can't use this perfect feature in my case.

So, my question is how to implement feature what I need in that complex world?

I don't have any idea how to do this. I also tried: providing different interceptors, decorate HttpClient, using factories and other stuff. Any of them give me same result.

UPD:

I also understand multi property in provider object. By this I can obtain all tokens provided in all modules, but I don't see whole solution. How I would be able to detect what exactly token from this array should be applied for specific http request (it can be from any module)?

Upvotes: 0

Views: 957

Answers (1)

Karlatt Itude
Karlatt Itude

Reputation: 59

Did you try the "providedIn : MyModule " syntax ?

from Angular source:

export interface Injectable {
  /**
   * Determines which injectors will provide the injectable,
   * by either associating it with an `@NgModule` or other `InjectorType`,
   * or by specifying that this injectable should be provided in one of the following injectors:
   * - 'root' : The application-level injector in most apps.
   * - 'platform' : A special singleton platform injector shared by all
   * applications on the page.
   * - 'any' : Provides a unique instance in every module (including lazy modules) that injects the
   * token.
   *
   */
  providedIn?: Type<any>|'root'|'platform'|'any'|null;
}

Upvotes: 1

Related Questions