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
  13. Struggling with QuickBooks error 6144, -301 ? Fix it by dialling us at 1-855-533-6333. The error usually arrives due to improper installation of QuickBooks upgrading.

    ReplyDelete
  14. Nice Information !
    Stuck with QuickBooks Error 2001? Don’t worry, give a call right to our Qb experts by dialling us at 1-855-662-2O4O.

    ReplyDelete
  15. I am never worried when you are handling my work. Before I found you I had a hard time getting the right programming homework help experts to work on my tasks. Most of the ones I got had plagiarized work and never completed on time. This time I am working on C++ and therefore I am looking for a C++ assignment help expert to help me compete with my assignment which is due in a week.

    ReplyDelete
  16. You are a statistics homework help who offers online classes. That is impressive. Tuition services are not mandatory for any student. But whoever sees tuition services can improve their class performance, especially for those students who find it hard to comprehend what is taught in a crowded classroom. I personally found it helpful when I was seeking econometrics homework help. I performed well.

    ReplyDelete
  17. Will you help me get an A in my economics assignment? I have not been able to get an economics homework help expert who can guarantee me an A. All I want is an expert who can guarantee me a top grade at a minimum price. In addition, I also want to know where you offer an economics assignment help class. I have missed so many classes and I am looking for a way to catch up.

    ReplyDelete
  18. Until now, I still don’t know why my image processing homework took too long to be completed. The Matlab homework help solver who handled it promised to deliver it in three hours but he took more than fifteen hours. It’s okay I will still use your Matlab assignment help again but how do I know you won't take that long to get the job done especially for assignments that have a tight deadline?

    ReplyDelete
  19. Hi, as an economics tutor do you offer economics assignment help? If yes, how do you handle revisions? I hired another economics homework help expert who wanted me to pay for revision. I didn’t understand that because to start with, it was they who had completed the assignment. If your revisions are free then I would be more than comfortable to hire you in my next paper.

    ReplyDelete
  20. How long does it take to change a tutor? I went to your website and chose a C++ assignment help expert based on the rating. The tutor is clearly knowledgeable and good at offering programming homework help. However, I do not understand his English. His English is so mixed and therefore explaining something to me is hard. I, therefore, would like to get a tutor from the United States whom we can clearly understand each other and also one who we are in the same time zone because of communication.

    ReplyDelete
  21. Hey, you are a statistics homework help . I have a task for you in my upcoming exam. Can you do my online exam? I will provide you with the notes and all materials that are needed in the exam. But I need one thing in return- A good grade. Whatever you do ensure that I score a good grade. It is on SAS and therefore if you can offer credible SAS homework help then I will know that I can rely on you in future.

    ReplyDelete
  22. Hello there, I am looking for a matlab homework help tutor, who has the ability to offer me quality matlab assignment help in control systems. I have a lot of pending assignments, but I don't want to fail in any of them and that is why I am seeking your help. If the quality of your solutions will be up to the standard, then I will hire you again and again.

    ReplyDelete
  23. We are the best website for providing Programming Assignment Help. Our years of knowledgeable team experts will help and guide students regarding their assignments.

    Programming Assignment Help


    ReplyDelete
  24. I found this one pretty fascinating, and you should go into my collection also. We provide Finance Assignment help services all over the world. I am impressed with your article. We appreciate that please keep writing more content. I am offering help to students over the globe at a low price.
    Finance assignment help
    help with finance assignment

    ReplyDelete
  25. Thanks for sharing this information. I have shared this link with others to keep posting such information to provide the best in class accounting assignment help online at very affordable prices.
    accounting assignment help
    help with accounting assignment

    ReplyDelete
  26. Many people are depressed about the problems of math homework writing. Well, don’t worry about that because we are providing this service at a very reasonable price.

    Math Homework Help
    Mathematics Homework Help

    ReplyDelete
  27. I found this one pretty fascinating, and you should go into my collection also. We provide Law Assignment help services all over the world. I am impressed with your article. We appreciate that please keep writing more content. I am offering help to students over the globe at a low price.
    Business Law Assignment Help
    Contract Law Assignment Help

    ReplyDelete
  28. Thanks for sharing this information. I have shared this link with others to keep posting such information to provide the best in class programming homework help online at very affordable prices.
    Programming Homework Help
    Python Programming Homework Help


    ReplyDelete
  29. I found this one pretty fascinating, and you should go into my collection also. We provide Programming Assignment help services all over the world. I am impressed with your article. We appreciate that please keep writing more content. I am offering help to students over the globe at a low price.
    do my programming assignment
    Programming Assignment Help

    ReplyDelete
  30. Many people are depressed about the problems of essay writing. Well, don’t worry about that because we are providing this service at a very reasonable price.

    do my python assignment
    python assignment helper

    ReplyDelete
  31. Thanks for sharing this information. I have shared this link with others to keep posting such information to provide the best in class assignment help online at very affordable prices.

    business assignment help
    business communication assignment help

    ReplyDelete

  32. Many people are depressed about the problems of essay writing. Well, don’t worry about that because we are providing this service at a very reasonable price.
    A text
    Engineering Assignment Help
    Engineering Assignment Help Services

    ReplyDelete
  33. I found this one pretty fascinating, and you should go into my collection also. We provide Assignment help services all over the world. I am impressed with your article. We appreciate that please keep writing more content. I am offering help to students over the globe at a low price.


    english homework assignments
    english help websites

    ReplyDelete
  34. Thanks for sharing this information. I have shared this link with others to keep posting such information to provide the best in class assignment help online at very affordable prices.
    Online homework help
    homework help services

    ReplyDelete
  35. It's weird to transform RxJS to promise. As for me this library is awesome. At least this is better promises. Check this out https://www.learnrxjs.io/

    ReplyDelete
  36. 여기에 게시 한 주제에 대해 정말 감사드립니다. 실제로 도움이되는 훌륭한 정보를 공유해 주셔서 감사합니다. 좋은 날! 먹튀검증

    ReplyDelete
  37. Thanks for sharing this information. I have shared this link with others to keep posting such information to provide the best in class homework help online at very affordable prices.
    Our online assignment help Australia service is an online assignment help service provided by experienced Australian assignment help expert at here.
    Edith Cowan University Assignment Help
    University Of New England Homework Help
    University Of Queensland Assignment Help
    University Of New South Wales Assignment Help
    University Of Melbourne Assignment Help
    Griffith University Assignment Help

    ReplyDelete
  38. Awesome Blog with informative concept. Really I feel happy to see this useful blog, Thanks for sharing such a nice blog...

    Looking for the best PPC course in Bangalore India? Learn PPC from Ranjan Jena, 10+ Years Expert Google Ads Trainer. 1000+ Students Trained @ eMarket Education, Koramangala, Bangalore.
    Best Online Digital Marketing Courses in Bangalore
    Digital Marketing Course

    ReplyDelete
  39. After study a few of the blog posts on your website now, and I truly like your way of blogging. I bookmarked it to my bookmark website list and will be checking back soon. Pls check out my web site as well and let me know what you think. marketing research assignment help

    ReplyDelete
  40. Great Article IoT Projects for Students

    Deep Learning Projects for Final Year

    JavaScript Training in Chennai

    JavaScript Training in Chennai

    The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

    ReplyDelete
  41. In such scenarios while getting stuck with any sort of technical or non-technical grievances in QuickBooks, simply call us on our QuickBooks Support Phone Number California +1(844)233-3033, and acquire exceptional accounting services from our executives. Our experts are skilled enough to answer all of the error codes users ask for.
    QuickBooks Desktop Support +1(844)233-3033
    QuickBooks Enterprise Support +1(844)233-3033
    Quickbooks 24/7 Customer service +1(844)233-3033
    Quickbooks Payroll Support +1(844)233-3033
    QuickBooks Technical Support +1(844)233-3033
    QuickBooks POS Support +1(844)233-3033
    Quickbooks Support Phone Number USA
    Quickbooks Support Phone Number USA
    c

    ReplyDelete
  42. In such scenarios while getting stuck with any sort of technical or non-technical grievances in QuickBooks, simply call us on our QuickBooks Support Phone Number California +1(844)233-3033, and acquire exceptional accounting services from our executives. Our experts are skilled enough to answer all of the error codes users ask for.
    QuickBooks Desktop Support +1(844)233-3033
    QuickBooks Enterprise Support +1(844)233-3033
    Quickbooks 24/7 Customer service +1(844)233-3033
    Quickbooks Payroll Support +1(844)233-3033
    QuickBooks Technical Support +1(844)233-3033
    QuickBooks POS Support +1(844)233-3033
    Quickbooks payroll support phone number +1(844)233-3033
    QuickBooks customer service +1(844)233-3033

    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 f

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.

Custom validation messages for HTML5 Input elements using the constraint validation API

HTML5 has introduced several input types such as EMAIL, URL, RANGE, SEARCH, DATE, TIME, etc,. Most of the modern browsers have implemented them and are ready to be used in a HTML document. Another exciting feature introduced in HTML5 is the form validation. Instead of writing JavaScript to validate users input, browsers can now validate it and show an appropriate message if the validation fails. The validation message is shown in line with the field for which the validation has failed. The default error message is shown when the validation fails. In this post I'll explain how these error messages can be changed.