Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the order of NgModule imports matter?

Tags:

I have been going through the Angular tutorial and when going through the HTTP section https://angular.io/docs/ts/latest/tutorial/toh-pt6.html and have noticed that the order in which imports are declared in the NgModule makes a difference in terms of whether or not the application works. I would like to know why that is.

In particular this works:


    @NgModule({
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        InMemoryWebApiModule.forRoot(InMemoryDataService),
        AppRoutingModule
      ],
    ... 
    }) 

but the following does not. The list of heroes does not get loaded. Note that the HttpModule is declared AFTER the InMemoryWebApiModule:


    @NgModule({
      imports: [
        BrowserModule,
        FormsModule,
        InMemoryWebApiModule.forRoot(InMemoryDataService),
        HttpModule,
        AppRoutingModule
      ],
     ...
    })

The tutorial is using Angular 2.4.4. I have noticed the problem in both Firefox and IE. I have not found anything in my google searches that would indicate the source of the problem.

like image 489
hashpyrit Avatar asked Feb 09 '17 19:02

hashpyrit


2 Answers

The order of providers matters. For exported components, directives, or pipes it doesn't matter, because conflicts result in errors.

The InMemoryWebApiModule.forRoot(InMemoryDataService), overrides Http, and if HttpModule is provided later, this overriding is rendered void. Providers added later override already registered providers with the same key.

like image 171
Günter Zöchbauer Avatar answered Oct 13 '22 20:10

Günter Zöchbauer


Yes. Order is important if one module depends on another.

like image 41
dats Avatar answered Oct 13 '22 22:10

dats