头图

APP_INITIALIZER is an instance of InjectionToken. It is a built-in injection token provided by Angular.

Angular will execute the function provided by this token when the application loads. If the function returns a promise, then angular will wait until the promise is resolved. This will make it an ideal place to perform some initialization logic before the application is initialized.

The Angular injector uses DI tokens to locate dependencies in Angular providers. We use the token to register the dependency in the provider:

 providers :[{ provide: token, useClass: SomeService }]

The token in the above code can be a type, a string, or an instance of InjectionToken.

  • Example of type:
 providers :[{ provide: productService, useClass: productService}]
  • String example:
 providers :[ {provide:'MESSAGE', useValue: 'Hello Angular'}]

When the type used is not 运行时表示 , such as injection interface, callable type, etc., it will use InjectionToken - the interface in TypeScript code, after compiled into JavaScript, the latter from the programming language level There is no such representation of interface. InjectionToken can be used at this time.

 export const HELLO_MESSAGE = new InjectionToken<string>('Hello Angular'); 
providers :[ { provide: HELLO_MESSAGE, useValue: 'Hello World!' }];

As mentioned earlier, APP_INITIALIZER runs when the application is initialized. Angular suspends application initialization until all functions provided by APP_INITIALIZER have run. If any of these initializers return a promise, then Angular waits for it to resolve before proceeding with App initialization.

This gives us the opportunity to connect to the initialization process and run some application custom logic. Runtime configuration information can be loaded. Load important data from background etc.

See an example. New file app-init.service.ts :

 import { Injectable }  from '@angular/core';
 
@Injectable()
export class AppInitService {
 
    constructor() {
    }
    
    Init() {
 
        return new Promise<void>((resolve, reject) => {
            console.log("AppInitService.init() called");
            ////do your initialisation stuff here  
            setTimeout(() => {
                console.log('AppInitService Finished');
                resolve();
            }, 6000);
 
        });
    }
}

Implementation of app.module.ts:

 import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
 
import { AppRoutingModule } from './app-routing.module';
 
import { AppComponent } from './app.component';
import { AboutUsComponent } from './about-us.component';
import { HomeComponent } from './home.component';
import { ContactUsComponent } from './contact-us.component';
 
import { AppInitService } from './app-init.service';
 
export function initializeApp1(appInitService: AppInitService) {
  return (): Promise<any> => { 
    return appInitService.Init();
  }
}
 
@NgModule({
  declarations: [
    AppComponent, AboutUsComponent,HomeComponent,ContactUsComponent
  ],
  imports: [
    HttpClientModule,
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [ 
    AppInitService,
    { provide: APP_INITIALIZER,useFactory: initializeApp1, deps: [AppInitService], multi: true}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

The above code uses InjectionToken APP_INITIALIZER to provide the function initializeApp1, which calls the init method of our service class.

Angular's dependency injection will inject dependencies into classes and components, but not into functions. And our initializeApp1 is a function that needs to inject AppInitService as a parameter. So we do this by using the deps flag and let Angular know that it needs to create an instance of AppInitService and inject it into the initializeApp1 function.

multi: true Create a multi provider DI token. This means that an array of providers can be provided for DI tokens.

If multi: false(默认值) is set and a token is used multiple times, the last registered token will overwrite all previous tokens. That is, a token can only have one provider.


注销
1k 声望1.6k 粉丝

invalid