Sometimes, you may need to load some simple data or do simple verification when the application is initialized. Most of the methods are to do this in the main component
component, but it is difficult to ensure effective use in other components. Is there an updated way to do this? Please continue reading. .
The official documentation describes this: APP_INITIALIZER is a function that is called when the application is initialized. This means that it can be configured in the form of a factory through the providers of the AppModule class, and the application will wait for it to complete loading before proceeding to the next step, so it is only suitable for loading simple data here.
ng new example --skip-install npm install # yarn install
First create a provider, which will return a Promise object after the request parsing is completed
@Injectable() export class JokesProvider { private joke:JokeModel = null; constructor(private http:Http){ } public getJoke(): JokeModel { return this.joke; } load() { return new Promise((resolve,reject) => { this.http.get(url) .map(r=>r.json()) .subscribe(r=> { this.joke = r['value']; resolve(true); }) }) } }
There will be three processes here:
The getJoke() method directly returns the data currently saved by joke when called by other components or modules
Private attribute joke will save the currently requested data
The load() function will be called immediately when the application is initialized
export function jokesProviderFactory(provider: JokesProvider){ return () => provider.load(); }
@NgModule({ declarations:[ AppComponent ], imports:[ BrowserModule,// required HttpModule// required ], providers: [ JokesProvider, { provide:APP_INITIALIZER,useFactory: jokesProviderFactory, deps:[JoesProvider], multi:true } ], bootstrap:[AppComponent] }) export class AppModule { }
<p>@Component({<br/> selector:'app',<br/> template:`<h1>Joke of the day: </h1><p>{{jokeModel.joke}} </p>`<br/>})<br/>export class AppComponent implements OnInit{<br/> title = 'app';<br/> jokeModel : JokeModel;<br/> <br/> constructor(jokesProvider: JokesProvider){<br/> this.jokeModel = jokesProvider.getJoke();<br/> }<br/> <br/> ngOnInit(){<br/> console.log('AppComponent: OnInit()');<br/> }<br/>} <br/></p>
The above is the detailed content of Understand the role of APP_INITIALIZER in Angular. For more information, please follow other related articles on the PHP Chinese website!