Angular Service Worker Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone welcome to this video in this video we'll turn an online-only angular application into an offline available one by adding a service worker and as you will see this is super easy to do with angular and I will show you how to turn into such an application and how you can then also configure it to fully meet your needs so let's dive in we'll start with this very simple angular application here and you can find the code to that project attached to this video and this is obviously a very well simple not too exciting angular app it is rendering a list of blog posts dummy blog posts which are fetched in our app component here from Jason placeholder well that is just a page exposing a dummy rest api which you can use to get some demo data to display on your page you can also send dummy post requests to them and so on but that's not what we'll do we'll focus on getting data so this is a normal angular app not too many features but it represents a typical angular app we got more than one component and we also got our posts and if you watch closely you see I'm also using some special font which I'm actually pulling in in my index.html file here I'm importing this a swelled font here from google fonts so this is what makes up our angular app now if we inspect it in chrome we can go to the application tab here in the developer tools and we can turn this to offline mode which means we're still online we don't have to quit our Wi-Fi network but this will simulate that we got no internet connection and if I now reload the page well obviously I get an error that we don't have an internet connection if I go back online it works again now let's see how we can actually fix this or change this behavior with the help of a serviceworker and how we can easily add such a serviceworker to the app with angular let's first of all understand what a serviceworker actually is now this is how our javascript code typically behaves it runs in a single thread that means our web application which can consist of multiple pages or in the case of an angular app with one page only this app often uses JavaScript and if you're using angular you're of course using JavaScript because angular uses JavaScript so this JavaScript code the entire angular app runs on one single thread and JavaScript has its features to still handle asynchronous code and not block the execution but this is all normal JavaScript now javascript and the browser also offers us to run an additional threat we can run a so-called web worker and a special form of baddest tea service worker on an average so this still then uses one of the same Fred but it's a different threat than your main JavaScript code and the important part is that this fred is kind of decoupled from your HTML pages so this means that this can also continue running in the background for example on your mobile phone that is something mobile browsers typically offer this can continue running and it could therefore also do advanced things like receive push notifications take my full progressive web app course if you want to learn more about this but one hour crucial thing that a serviceworker can do is it can manage all your different pages in case you got multiple pages or you're a single page if you're building an angular app and it can listen to outgoing networks requests so it can listen to requests going out of your web page for example if you are fetching the assets of that web page the CSS code the font JavaScript or also data from an API the serviceworker can catch these outgoing requests and do something with them like for example cache the responses in a special cache storage or then also return these cached responses back to your page so that it also works if you've got no internet connection of course only if there is a cached version available this is what the serviceworker does it can be seen as a proxy between your app your front-end app and DD HTTP requests you are sending to the backend it proxies that request which means it caches it does something with it and might then allow it to still go on and leave the app but it could also block this now configuring such a serviceworker and writing it from scratch is something you can do and something you learn in my full progressive web app course there you also learn about features like push notifications and so on for this video we'll focus on how angular can easily add such a serviceworker to our angular app because it turns out that there is a special package we can install for that let's quit ng surf and now here it's important that you're using the latest CLI version for that project and this project does and then you can run ng add to add a third-party package but that's more than just the NPM library really some functionality to your app and only some features can be added because essentially this will execute a command which has to be defined by whichever package you are targeting so not every not even close not every third-party library supports this feature but there is a special library which does support it which you can target with at angular /pwa and if you run this this will actually configure your existing project to use the angular Service Worker package and start with a pre-configured Service Worker so it does a lot for you you can already see it added some things to the index.html file like the no script section to give a warning if JavaScript is turned off because we need that of course we need to turn on it loads this manifest here which is also generated now that is important for actually having a launcher icon for your app if you have it on a mobile phone you can even save it to the home screen and then start it with that and you can define which icon that should use and so on so dad is the manifest or JSON file again learn more in that course I mentioned for us interesting is the app module because in the app module we are using a serviceworker module which is imported from at angular serviceworker and this is really an official package of the angular framework and it does what it sounds like it registers a service worker which will be that proxy that caches outgoing requests and does something with them and you will learn how to configure what it does to them later in this video of course we use it here by calling the register method and there we target the ng SW worker dot J's file and you won't find that file here and the reason for that is the this file will actually be auto-generated it will be generated during the build process and it will be in a dist folder therefore and it will hold your serviceworker which will contain a lot of functionality which you don't have to and typically don't want to write on your own and here it's all the configure to only be added if you're building for production in the assets folder we see some icons were added for that manifest a JSON file and in the root project folder we see that in the package to chase the file something changed for example the angular PW a package was added which includes that angular Service Worker package and we got this ng SW config file this is the file where you can configure that serviceworker which will be generated but we'll take a closer look at this in a second the angular JSON file which manages to see live project all that was adjusted a little bit there serviceworker is set to true for the production build this is required because the serviceworker will cache certain resources and to ensure that a new belt updates the serviceworker these resources will contain a hash and dad will then also be injected into the serviceworker which is why we need to make the build process aware of the fact that we need a serviceworker this is how that works now let's simply see that in action let's create a production build by running energy built - - prod and this will now bundle and optimize the entire app use ahead of time compilation and so on and it will spit out our angular app in a dist folder and there we should then also see the serviceworker so let's have a look to close the source tab here let's refresh here's the dist folder the angular PWA folder for the project and there we see that ng SW work or Jas file you remember that is the file we are importing in the app module here we're registering it here so this can be found in the dist folder indeed if we have a look at it you see there's a lot of code in there because well it's actually pre generated for you to do all that caching and so on in a very efficient way and now let's simply do what it let's simply see what it does and for that you need a web server you can run to host your production app here you could do that with ng surf - - brought but there you will actually not see the serviceworker in action correctly because we'll only build it in memory so therefore what you should do is install a lightweight node server and thankfully there is one you can install it with npm install' - g to install it globally HTTP server this is a package you can use to launch a simple node based server which will host the content of the folder you run the command in and to command you need to run it's just HTTP - server so let's navigate into our disk for and there in the angular PWA folder and let's run HTTP server and then you can assign a port with - pata t1 for example and we'll then bring this up and now you can visit localhost 8080 one and you should see your angular app there now this app looks like a normal app now reloaded wants to make sure that the service worker can do its work and go to application again we should now see that under application we got that energy SW worker running and if you don't see that try reloading that page one more time also make sure to clear the storage here entirely if you were it with service workers and Dysport served on your local domain before now you should see that the interesting part is if I now take offline again and I reload it still works right we still see the same content as before even though we're offline now how can that work if we go to the network tab and we clear it and we now reload we see we're making a bunch of requests here and they're all essentially served from the ng service worker here so from the service worker this is all served the interesting part is the post request here probably which is still kind of can connect to the outgoing server for that let's again disable Wi-Fi and let's try this again and now this does not work but what we can see still is that for one buggerin intended behavior in chrome which leads to these API requests still going through even if we simulate offline mode but more interestingly we see a white page we don't see that there is no internet connection error now we would not just see a white page we would see any content we adhere in if we load our page so we essentially see everything that's hard-coded into our angular app the dynamic content is missing we'll take a look at this in a second but all the hard-coded content is there because what we can see in the network tab is that we're loading the main page the Styles not the font but the Styles the JavaScript files all that is loaded from the service worker and the failing things are the font and our posts let me turn Wi-Fi back on and also leave that simulation mode which didn't work too great I guess and now of course if I reload it again works and let's now change something first of all let's change something at the app component there I'll add a h1 tag where I say my posts now let's quit set HTTP server go back into the main folder and let's run ng build dash dash prod again and let's see how this now changes the app and if I'm right regarding my statement that hurt coded content would be cached so let's wait for this to finish for that bill to finish and once it's finished let's go back into that dist folder and there into that angular PWA folder and let's run our server command again so HTTP server on that port let's reload the application here and you might need to reload twice and you should tend to see my posts the reason for that double reload is that the serviceworker was loaded and the serviceworker is aware of the fact that the index.html file a file changed or that the script rendering content to it changed to be precise because of that hashing thing I mentioned this hash table which is automatically generated and all the files having hashes because by default it would of course fetch these resources from the cache so we would see the old version we don't want that so we take the new version by or we let us give the new version by using that angular Service Worker package which takes care about that hashing and the fact that the service worker is aware of the new version for us so we get that now if I go offline again you see that is also part of the loaded page and if I go fully offline by treating off Wi-Fi we still see that so now the font and the API call the API data is missing I should say so that is what I now want to change and to change this and get that same page here when we're offline whereas I'm getting when I'm online we need to change the serviceworker config which can be done in the ng SW conflict or JSON file now in this file you can configure how the angular service worker behaves so let's take a closer look now this file is actually not that long it's adjacent file JSON format and first of all we have the index page this indicates what is the root page of our app we want to cache and load and that of course is the index.html file sitting directly in the root server folder were serving from and then we get a so-called asset group or actually asset groups it's an array and in there we got two s of groups these objects which we have in there now asset groups are configurations that define which static assets should be cached and how they should be cached dynamic assets for example would be the data from the API so data we're fetching which might change on that API so it's not static it changes frequently our HTML file our JavaScript code will also change with every build but after the build it's static it's not changing in some database or anything like that so that's what an acid group is we can give such a group a name whichever name you like and you can then define how it should these assets below that prefetch means that when your page loads angular will go ahead or the serviceworker will go ahead and already prefetch all the assets which are specified in this asset group which means it puts it into cache even if you haven't yet the alternative to prefetch is lazy you can use that too and dad would only load them once you needed them at least once the advantage of lazy is of course that you don't occupy all the bandwidth right at the beginning the downside is that if you need it for the first time it will not be there so if the user loses the internet connection before the asset let's say the CSS file is required the first time it will not work because it will not be cached with prefetch it will be cache even before you need it there also is a update mode I guess you can see it down there now this is important for the case that you're pushing a new version of your angular app and therefore also of your serviceworker to your server and the user is already browsing on that server and it will get informed about the new service worker and now the service worker can already prefetch the updated assets or also load them lazily when they are required now the assets which should be loaded are the resources then resources has one key property the files and there you have an array pointing to the files you want to cache you can point at something like the index.html file and this has always seen relative from the dist folder so from the folder you will have in the end once you deploy this but you can also set up patterns like every CSS file or every javascript file in the root folder or you could say every CSS file in any subfolder this is what this pattern would say so you can also set up glop patterns like this or directly point at the file you want to use without the hash because you can't know the hash in advance angular will generate that automatically will take the unhatched filenames here and then automatically generate a serviceworker which will take the hashes into account now here we get a second asset group for well basically all images we got and so on it differs from the first one in regarding the fact that it's only pre loading that if we need them if we wizard to them or use them at least once and this is leading to the behavior we have right now now we got one our static asset which is not included here and that is our external font it's not changing or at least not regularly so we can treat it as static but it's not included here because it's not one of our files but we can take it from the index.html file by just copying that entire link which will be requested eventually and then we can go back to the ng SW config file and there we tell angular that we also want to cache this now we don't add it to files because this is for local faults there is an additional resource type you can define and that is URLs it's also an array of strings but here we put URLs like this one which are reaching out to our servers to we then fetch resources from there with that edit let's save that file quit your server down there and let's go back into our root project folder and let's create an a verb illed with ng build prot like this and once this is done and we revisit the dist folder and surf that again we should see that the font is also loaded in an offline mode so we go into the dist folder into angular PW a rerun that HTTP server command and let's reload that page and with it reloaded and you might also close it and open a new tab to ensure that the new service worker gets really loaded and it's not still using an old one with that loaded you can take that offline box here again or since I always needed to do that simply turn Wi-Fi off go to the network tab to see all requests and reload the page and now you should see that the font here alt is not marked as red but is actually loading the font as it should so this is now also working it's now also fetching this and we're still our now again able to use it in offline mode that font now what about the API regarding the API we can all to prefetch this for that we add a new configuration item and that would be data groups remember we got asset groups here for the static files essentially data groups is for dynamic data so typically data you request from an API data that might change frequently how a data group configured it is an array because it's data groups here but one day the group is then again an object just as an asset group you then define a name of your choice like posts but that name is totally up to you and then your defined you are else you want to handle with this group and in my case that is the URL I can see in my app component which is where I make this HTTP request this URL to Jason placeholder this is what I'll take and this is what I'll put into the URLs array as a string you could now also add a version here if you got an API which might have different versions and diversion changed then you could lock the version in here too for example cache different data pieces side-by-side for different API versions here I will not use the version and instead what you can add here is a cache config this is another object where you can now in detail configure how this data should be cached and for that you can for example set a max size this is a number and this defines how many entries do you want to cache and now that's important this does not mean how many posts for example this means how many responses now for this single URL we will only cache one response at a time but if you had a more generic URL with a star let's say for different endpoints then you might want to make sure that only 410 outgoing requests the answer was cached to not pollute your cache and grow it infinitely because your space is actually limited and managed by the browser so you don't want to cache everything so here we could say cache five responses again for this example it doesn't matter we can then also add max age to define how old should the data in the cache be before we get rid of it and definitely fetch new data because you might want to fetch from cache first to deliver something onto the screen as quick as possible and then maybe reach out to more up-to-date data behind the scenes but for dad you of course need to know is the data in the cache still valid or should I always fetch new data this is defined as a string which you write like this you could say one day or 12 hours or 50 minutes this is essentially the format you have details can be found in the official Docs and you'll find a link to that attached to this video too so here I'll go with let's say six hours and then you can also add a timeout the timeout is defined in the same way and there you could say if I'm waiting for a response for let's say 10 seconds already then I want to fall back to the cache and not wait longer but I don't want to use the cash immediately I want to wait for these 10 seconds at least so you could say 10 seconds here last but not least and that's important because it works together with the above values the strategy there you can have two types of strategy freshness which means always try to reach out to the back and first and only use the cache if you're offline or performance performance tries to get something onto the screen as quick as possible and it will take max-age into account you know whether it should absolutely reach out to the back end or just use the cache value on the other hand freshness will take time out into account to know how long to wait for a response before it uses the cache so I will go with freshness here and I will save this and now you know the game let's go back and let's build this again with - - prod and what we should see is that now that we built this that if we then go back to the build project and serve it that this actually then works in offline mode so let's bring up that HTTP server reload this page and as I mentioned before feel free to close it because a new service worker to be registered should also be able to be loaded without you closing that tab and opening a new one angler can handle that but by default this is required by default for a new service worker to go active or to turn active and do its job you need to reload the page also because angular does not use the new updated code you might ship onto the server and load it into your already yep because that might break your already running app so close the tab open a new one now in a new tab reload at least once so that the API responses can be cached the first reload loads the serviceworker the second one loads the API responses then turn off the Wi-Fi and load again and what you should see is that you still got your post here now one thing you can notice is that the fonts are missing because and that's just something you have to know about google fonts the way it's loaded it takes cue URLs this is the URL where it goes to and tries to fetch the font then the other URL we put in there is the one which just holds the rules for the font and then that extra URL so let's add that newly gathered information here now replace this at the end here with star star to load any funds from the URL close the HTTP server and built this one more time as you'll saw it before with anji build - - prod and we could already see that the API data was loaded at least so that this was present now if this built one more time let's again go back to our distillate surf this one more time but then open a new tab for it to become active reload this one more time to store to make sure that the response is already stored I should say and now let's go offline again and reload this app and you see the fonts are there - and in the network tab we see everything is fetched the posts fail but that's the problem because we take that from the cache which works you can see it here in response there it is and this is how we can use the serviceworker the angular serviceworker package which you can easily add with the ng @ @ angular pw a package which includes that serviceworker package which also gives you that many faster json file and which overall is something you have to learn but then gives you the powerful tool of making your web app offline available now check the official Docs which you find attached to the video of course and I hope that this was helpful
Info
Channel: Academind
Views: 51,120
Rating: undefined out of 5
Keywords: angular, angular2, angular 2, angular 6, angular 4, service worker, angularjs, angular.js, angular javascript, offline, angular offline, @angular/service-worker
Id: 5YtNQJQu31Y
Channel Id: undefined
Length: 27min 10sec (1630 seconds)
Published: Wed Jun 06 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.