Skip to main content

How to use the APP_INITIALIZER token to hook into the Angular bootstrap process

I've been building applications using Angular as a framework of choice for more than a year and this post is not about another React vs Angular or the quirks of each framework. Honestly, I like Angular and every day I discover something new which makes development easier and makes me look like a guy who built something very complex in a matter of hours which would've taken a long time to put the correct architecture in place if I had chosen a different framework. The first thing that I learned in Angular is the use of the APP_INITIALIZER token.

The documentation at angular.io says - 'A function that will be executed when an application is initialized'. It does not spew any details on how to use this function and where to include it.

Sidenote: I must say the documentation could've been better with examples and a detailed explanation for the given feature could've helped. But hey, I can't hold this against you Angular :)

The APP_INITIALIZER token is used when you want to get the application's configuration details from an API and keep it ready before the application renders the page. For example, you would want to load the necessary language files before rendering any of the templates or you would want to resolve a remote API which provides information on the environment that the application is being run on. It's similar to how the 'resolve' attribute in the router's configuration is used to get data from the remote API and feed it into the route's 'data' source. In this case, the remote API is resolved first and then the application continues with the bootstrap process.

Here's an example of how the APP_INITIALIZER token is included in the application. The main module of the application - app.module.ts includes the APP_INITIALER in its 'providers' section:


Notice that the 'providers' section includes APP_INITIALIZER with the attribute 'useFactory' referring to factory function 'initApp'. Here's the definition of the initApp factory function:


The factory function is expected to return a Promise and only after the promise has resolved the application bootstrap process would continue. In the above code snippet, a delay of three seconds is added before the promise resolves. This blocks the bootstrapping of the application for three seconds. Similarly, you could use an HTTP service (from HttpClient) to request data from an API and only after the request is complete that the application bootstrap process would continue. However, to use Angular's HttpClient in the initApp factory function, include HttpClientModule in the imports section and also specify HttpClient as a dependency (deps) to the APP_INITIALIZER provider:

imports: [
  BrowserModule,
  HttpClientModule
],
providers: [{
  provide: APP_INTIALIZER,
  useFactory: initApp,
  multi: true,
  deps: [HttpClient]
}]
...

Next, update the initiApp factory function and use the instance of HttpClient to request data from a remote service:


The 'get' method on the HttpClient instance returns a Subscription (see RxJS) and the toPromise method is used to convert the Subscription to a Promise. If the factory method returns the subscription, the application would continue to bootstrap as if there was no APP_INITIALIZER token added to the module.

The source code for the above example is available at - https://github.com/sagar-ganatra/angular-app-initializer

Comments

  1. The type of paper writer service you're looking for will be provided to you within the deadline offered to you. Writing quality paper writer is the principal role of our services. Include the class name and number that is about the paper writer service
    . If you are searching for top essay writing companies, try out the mentioned above. Now you can get genuine college paper writing service online, one that is going to fit your financial plan and get your work done too.

    ReplyDelete
  2. can this also be used to fetch user details/settings on page refresh after user is logged in?

    ReplyDelete

  3. اعالى الخليج تقدم افضل خدمات نقل العفش الدولى المتميزه باسعار متميزة ومنها :

    شركة شحن عفش من الرياض الى دبي
    نقل عفش من الرياض الى الاردن شحن عفش من الرياض الى الاردن

    ReplyDelete
  4. Thanks for the information...
    Best SEO Training in Bangalore - BTM Layout | Learn SEO from Experts - Best SEO Training in Bangalore - Learn Advanced White Hat SEO (Search Engine Optimization) Techniques from Expert Working Professionals,
    Excel in On-page & Off-page Optimization Techniques, We Provide Real-Time Training with Case Studies on Live Projects along with Certification.

    ReplyDelete
  5. Thanks for the information...
    Visit Our Website - Best Digital Marketing Training in Bangalore - i Digital Academy is a leading Digital Marketing Training Institute
    in Bangalore Offering Placement Oriented Digital Marketing, SEO and Web Development Courses.




    ReplyDelete
  6. This is a great article with lots of informative resources. I appreciate your work this is really helpful for everyone. Check out our website Google Search Api for more related info!

    ReplyDelete
  7. Thank for this blog are more informative contents step by step. I here by attached my site would you see this blog.

    7 tips to start a career in digital marketing

    “Digital marketing is the marketing of product or service using digital technologies, mainly on the Internet, but also including mobile phones, display advertising, and any other digital medium”. This is the definition that you would get when you search for the term “Digital marketing” in google. Let’s give out a simpler explanation by saying, “the form of marketing, using the internet and technologies like phones, computer etc”.

    we have offered to the advanced syllabus course digital marketing for available join now

    more details click the link now.

    https://www.webdschool.com/digital-marketing-course-in-chennai.html

    ReplyDelete
  8. This article to good. Thanks for sharing information.

    Web designing trends in 2020

    When we look into the trends, everything which is ruling today’s world was once a start up and slowly begun getting into. But Now they have literally transformed our lives on a tremendous note. To name a few, Facebook, Whats App, Twitter can be a promising proof for such a transformation and have a true impact on the digital world.

    we have offered to the advanced syllabus course web design and development for available join now.

    more details click the link now.

    https://www.webdschool.com/digital-marketing-course-in-chennai.html

    ReplyDelete
  9. This is really very nice post you shared about the APP_INITIALIZER token to hook into the Angular bootstrap process, i like the post, thanks for sharing. Learn best Ethical Hacking Course in Bangalore

    ReplyDelete
  10. I finally found great post here.I will get back here. I just added your blog to my bookmark sites. thanks.Quality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing.Learn best Ethical Hacking Training in Bangalore

    ReplyDelete
  11. Get the best Dissertation Writing Services at fullassignment.com for student can take help for homework. We provide Assignment Help such as : Doctoral Dissertation Help , Dissertation Help , Dissertation consulting Help , Research Dissertation Help . We offer 100% plagiarism free, on-time delivery. We have the best experts for you can take help for homework.
    For more info please visit our website: https://fullassignment.com/
    WhatsApp : +1-6692714848

    ReplyDelete
  12. Great blog, thanks for sharing with us. Ogen Infosystem is a leading web designing service provider in Delhi, India.
    Website Designing Company in India

    ReplyDelete

Post a Comment

Popular posts from this blog

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code.

What is Minification?

Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript file…

A cheat sheet of keyboard shortcuts in ColdFusion Builder

In my last post I have explained about keyboard shortcuts in ColdFusion Builder 2.0. This blog post contains a list of all shortcut keys and I have listed these keyboard shortcuts based on the categories that it falls into. Well, this post was not planned since users can easily get to know the keyboard shortcuts by navigating to the preferences (ColdFusion -> Profiles -> Keys). However, I met Joshua at Scotch on the rocks in Edinburgh and he suggested that it would be nice to have the list of keyboard shortcuts handy. So this post is for those who would like to have the list with them and refer it whenever required.


Keyboard shortcuts for inserting text:

These are the keyboard shortcuts which are used to insert some text into the editor:

CommandKeyboard shortcuts on WindowsKeyboard shortcuts on MacInsert anchor tagCTRL + T, LCMD + T, LInsert bold tagCTRL + T, BCMD + T, BInsert br tagCTRL + T, RCMD + T, RInsert cfabortCTRL + T, ACMD + T, AInsert cfdumpCTRL + T, DCMD + T, DInsert cfs…

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.