<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Enrique oriol on Medium]]></title>
        <description><![CDATA[Stories by Enrique oriol on Medium]]></description>
        <link>https://medium.com/@enriqueoriol?source=rss-97e2a8b4454------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dOnVfjbDzBuvMQw3.jpg</url>
            <title>Stories by Enrique oriol on Medium</title>
            <link>https://medium.com/@enriqueoriol?source=rss-97e2a8b4454------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:31:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@enriqueoriol/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Angular 5 Universal + Firebase]]></title>
            <link>https://medium.com/angular-in-depth/angular-5-universal-firebase-4c85a7d00862?source=rss-97e2a8b4454------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c85a7d00862</guid>
            <category><![CDATA[universal]]></category>
            <category><![CDATA[angular-universal]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <dc:creator><![CDATA[Enrique oriol]]></dc:creator>
            <pubDate>Tue, 24 Apr 2018 22:06:25 GMT</pubDate>
            <atom:updated>2020-04-30T00:26:30.645Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Universal &amp; Firebase functions: The missing guide</h3><blockquote>Have you ever tried to build Angular Universal in your project for the first time? It wasn’t easy at all, right?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8QUF097Cy8F39cjUCbgMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*NfPm9mxzAD9n0M0M.png" /></figure><blockquote><a href="https://medium.com/angular-in-depth"><strong><em>AngularInDepth</em></strong></a><strong><em> is moving away from Medium. More recent articles are hosted on the new platform </em></strong><a href="https://indepth.dev/angular/"><strong><em>inDepth.dev</em></strong></a><strong><em>. Thanks for being part of indepth movement!</em></strong></blockquote><p>Lucky you, I’ve written this <strong>simplified guide to configure Angular 5 Universal</strong> in your Angular project.</p><p>Moreover, I’m gonna give you also a <strong>bonus track</strong> on <strong>how to run Universal in a serverless environment like </strong><a href="https://firebase.google.com/docs/functions"><strong>Firebase Cloud Functions</strong></a>.</p><h3>Angular 5 Universal guide, step by step</h3><p>If you haven’t heard about Angular Universal, it is a <strong>Server Side Rendering (SSR) </strong>tool that allows you to render your Angular app from a server.<br>Main benefits of SSR are SEO results and reducing initial page load time.</p><blockquote>In the past, it was quite complex, but now, Angular CLI v1.6 makes adding Universal to your project easier than ever.</blockquote><p>This is gonna be a step-by-step guide, so… let’s start!</p><h4>1 — Angular CLI 1.6+</h4><p>First, you’ll need a recent version of Angular CLI (CLI 1.6 or higher).<br>To install/update your CLI, run from terminal:</p><pre>npm install -g @angular/cli</pre><h4>2 — Angular project</h4><p>If you don’t already have a project, create one using the recently installed CLI. Run from terminal:</p><pre>ng new my-project</pre><p>Done? Then go to next step.</p><p>Otherwise, if you have a project with an older version of CLI, you can update it like this:<br>2.1 — Open <em>package.json</em> file<br>2.2 — Modify the version of the <em>“@angular/cli” devDependency </em>to match the most recent one (<a href="https://www.npmjs.com/package/@angular/cli">this one</a>).<br>2.3 — Remove the <em>node_dependencies</em> folder from your project<br>2.4 — Install dependencies again running “<strong><em>npm install”.</em></strong></p><h4>3 — Creating Universal with the CLI</h4><p>Go to terminal and run:</p><pre>ng generate universal</pre><p>This command should create the following files:</p><ul><li>src/app/<strong>app.server.module.ts</strong></li><li>src/<strong>main.server.ts</strong></li><li>src/<strong>tsconfig.server.json</strong></li></ul><p>The first 2 files are like the entry point of your app for server-side execution. The third one is the TS configuration in order to compile your app in a NodeJS environment.</p><p>Also, following files should have been updated:</p><ul><li><strong>package.json</strong>: Adds a dependency</li><li><strong>.angular-cli.json</strong>: Configures the CLI in order to compile the Universal app bundle.</li><li><strong>src/main.ts</strong>: Waits to load SSRDOM before rehydrating Angular locally</li><li><strong>src/app/app.module.ts</strong>: Link both Angular versions for rehydrating purposes</li><li><strong>.gitignore</strong>: Ignores new outputs that will be generated during build stage.</li></ul><h4>4 — Install the new dependencies</h4><p>The previous command has added `@angular/platform-server` to your dependencies, but it has not been installed.</p><p>Install them by running:</p><pre>npm install</pre><p><strong>What have you achieved, right now?</strong></p><p>Well, at this point you have the basics to build Angular code that can be executed also in the server. Looking carefully <em>.angular-cli.json</em>, you’ll see that a new app has been added to the configuration. It will generate the Universal bundle and move it to <em>dist-server</em> folder.</p><p>You can see how it compiles, by running on terminal:</p><pre>ng build --prod &amp;&amp; ng build --prod --app 1 --output-hashing=none</pre><p>That command should build 2 folders:</p><ul><li><strong>dist</strong> folder: with the original Angular app</li><li><strong>dist-server </strong>folder:<strong> </strong>With the Universal version of your app, compiled for execution on the server.</li></ul><p>However, that’s not enough to get SSR. <strong>You’ll need a server that is in charge of rendering the Universal version</strong> when it get’s a request. That server can be build using NodeJS, <a href="https://github.com/angular/universal">but other technologies can also be used instead</a>.</p><p>I’m gonna show you how to create the server using <a href="http://expressjs.com/es/"><strong>Express</strong></a>, a well know NodeJS framework.</p><h4>5 — Add additional dependencies</h4><p>In order to use Express, you’ll need to install some more dependencies:</p><ul><li><strong>express</strong> — <em>Express framework</em>.</li><li><strong>@nguniversal/express-engine</strong> — Angular Universal Adaptor for <em>Express</em>.</li><li><strong>@nguniversal/module-map-ngfactory-loader</strong> — Dependency for <em>lazy-loading</em> routing from server.</li><li><strong>reflect-metadata</strong> — Dependency required for some polyfills.</li></ul><p>You can install them on terminal:</p><pre>npm install --save @nguniversal/module-map-ngfactory-loader @nguniversal/express-engine express reflect-metadata</pre><h3>6 — Create the Express server for SSR</h3><p>In project root, create the server folder. Inside, create a new file server/<strong>index.ts</strong> with this content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c83e95bfc4b428768e9e967cc3ec993/href">https://medium.com/media/4c83e95bfc4b428768e9e967cc3ec993/href</a></iframe><p>What you see here is a really simple Node server, built with Express framework. Talking about Express would take several posts.</p><p>Here I’ll only detail here a few basic points covered in the code:</p><ol><li>You’ve created the server by calling the express() function. Then, you set the result in the app variable.</li><li>The <em>promise</em> returned from ngExpressEngine is passed as a HTML render engine. That function is a <em>wrapper</em> that helps you by:<br>2.1 — Internally call renderModuleFactory: the one that renders the HTML on client requests.<br>2.2 — Initial param is AppServerModule, the Angular module you&#39;ve just created.<br>2.3 — You can pass additional <em>providers</em> with data that would only be retrieved by the current running server.</li><li>You are using app.get() in order to filter HTTP requests:<br>3.1 — In this case, any static file (urls ending with some extension, in glob syntax, the pattern *.*), would be served from dist folder. Webpack would move there the static files required (JS, CSS, imgs) thanks to the changes made by ng generate universalin <strong>angular-cli.json</strong> file.<br>3.2 — The remaining routes would be passed to the server as simple navigation.</li><li>Call app.listen to run the server.</li></ol><h3>7 — Typescript Compiler</h3><p>You’ve created the Express server by using Typescript, so you’ll need to compile the TS code into plain JS.</p><p>On frontend, you are used to creating bundles with minified code, all together in a single file. This approach makes sense for client code because you are reducing the size and number of files to send. However, this approach does not make sense at all for server environments.</p><p>NodeJS has a quite efficient modules architecture, and it is loading files locally: Building a bundle with Express dependencies would only serve to increase compilation time.</p><p>As building a bundle does not make sense in Node environments, what I suggest you is to only compile <strong>index.ts</strong> file, in order to convert it to plain JS.</p><p>Compiling one file with TS CLI is dead easy…</p><p>Check that you have the latest TS CLI, running on terminal:</p><pre>tsc --version</pre><p>Otherwise, install it with:</p><pre>sudo npm install -g typescript</pre><h3>8 — Configuring server TS compiler</h3><p>Typescript would need to know how do you want to compile the server code. You can detail that by creating a config file:</p><p>In server folder, make a tsconfig.ssr.json file with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc36d86c8e80b254fe86aa3f334e99a3/href">https://medium.com/media/bc36d86c8e80b254fe86aa3f334e99a3/href</a></iframe><p>This config should compile server/index.ts TS file for Node (that&#39;s the reason of using <em>commonjs</em> modules). The result will be placed on the dist-serverfolder.</p><h3>9 — Adding compiler commands to package.json file</h3><p>Open package.json file and in the scripts zone, write:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84222f16d8284c03b0a69000e48011c0/href">https://medium.com/media/84222f16d8284c03b0a69000e48011c0/href</a></iframe><p>You’ve just created 4 commands that you can run with <strong>npm</strong>:</p><ul><li><strong>tsc:server</strong>: Compiles the Express server using the previous config file.</li><li><strong>build:client-and-server-bundles</strong>: Compiles your Angular app production ready and using <a href="https://angular.io/guide/aot-compiler">AOT</a>, both browser and server versions.</li><li><strong>build:universal</strong>: Useful command that calls the previous ones. That’s just what you need to prepare the SSR stuff.</li><li><strong>serve:universal</strong>: Runs the Express server you’ve just created.</li></ul><h3>10 — Testing the results</h3><p>Everything is ready, now you have to try it!</p><p>Let’s start by compiling. Run on terminal:</p><pre>npm run build:universal</pre><p>That should compile the client version of your Angular app, an alternate version for servers, and your Express server itself. Now run:</p><pre>npm run serve:universal</pre><p>ta-daaaaaaa! If you started from scratch, that’s what you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*SvHQNInJJt7vC4GY." /></figure><p>-But… How do I know if what I see has been rendered on the server instead of the client?</p><p>-Nice doubt! Thanks for asking!</p><p>If everything’s gone fine, Angular Universal should have rendered the page from Express server, before sending it to your browser. The SSR content should have been loaded in your browser, while the Angular client version is being loaded in background. Once finished, Angular should have linked the client app with the SSR app, in a process called rehydration.</p><p>If for any reason the server has not been able to render the page, you are probably watching the same result, except it has been directly generated from the client(no <em>SSR</em>, neither <em>SEO</em>).</p><p>Then… <strong>how can I check whether Server-Side Rendering is being used or not?</strong></p><p>Easy peasy. Right-click on the browser page and select “View page source” option. Other browsers than Chrome have also similar features.</p><p>If you are using SSR, your whole website should be shown inside the &lt;app-root&gt; Angular tag. Like in this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*YOtTIlGlX4S53bQz." /></figure><p><strong>However, if something went wrong and SSR failed, you should see an empty </strong><strong>&lt;app-root&gt; tag.</strong> That&#39;s the indicator that SSR is not working and that you are watching a client rendered page.</p><figure><a href="https://www.udemy.com/angular-components-like-a-pro/?couponCode=BLOGREADER"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*50YFHkigSO3y20qaNYnzDA.png" /></a></figure><h3>Bonus Track: Deploy on Firebase</h3><p>For this section, I’m assuming a basic knowledge of Firebase and that you have already created an empty Firebase project. Otherwise, please, go and <a href="https://firebase.google.com/">create a Firebase user and add a new project</a>.</p><h3>1 — Installing Firebase CLI</h3><p>Run the command below to install or update Firebase CLI:</p><pre>npm install -g firebase-tools</pre><h3>2 — Login with Firebase</h3><p>Run in console:</p><pre>firebase login</pre><h3>3 — Add Firebase to your project</h3><p>From Angular project folder, run this command:</p><pre>firebase init</pre><p>In the dialogue, mark <strong><em>Functions</em></strong> and <strong><em>Hosting</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*SMFY2MbBWAklsRpc." /></figure><p>Then, pick the Firebase project you want to link the project with.</p><h3>4 — Firebase functions</h3><p>You’ll be prompted about using TS or JS. As you have already created the TS server compiler config, you can just pick JS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*9ybSSiZHY2-pRA3l." /></figure><p>Regarding ESLint, you can say “no”, as well as with npm dependencies install.</p><p>Tell Firebase that public directory will be <strong>dist/browser</strong> (we will update that ASAP). Tell Firebase it will be an SPA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*iGvc0sG3459gZ7Z0." /></figure><p>Once the process is finished, you’ll have a functions folder. That&#39;s not the structure you want. In fact, the only thing you really need from this process is the package.json file.</p><p>Ok, you’re done with the easy part. But now, you need to connect Firebase functions with your Express server and give it access to the files you’ll upload to Firebase hosting.</p><p><strong>Let me tell you what, </strong>in my opinion,<strong> is the optimal way to use together Firebase and Universal.</strong></p><h3>5 — Firebase functions structure for Universal</h3><p>Right now your compiled code is distributed between dist and dist-server folders. Moreover, Firebase has created a functions folder, where it expects your <em>cloud functions</em> to live (basically your Express server and its dependencies).</p><p>So at this point, your build structure looks like that:</p><ul><li><strong>dist</strong>: Angular (browser) App and static files</li><li><strong>dist-server</strong>: Universal App</li><li><strong>functions</strong>: Express server and dependencies</li></ul><p>However, you want the Express server to run from Firebase functions, and it needs to read the Universal App. This structure does not allow it to access that folder.</p><p>I suggest you to use this other structure instead:</p><ul><li><strong>dist</strong>: Express Server and dependencies<br> — <strong>browser</strong>: Angular (browser) App and static files<br> — <strong>server</strong>: Universal App</li></ul><p>So…</p><p>5.1 — Remove dist and dist-server folders</p><p>5.2 - Now, make a new empty dist folder.</p><h3>6 — package.json for Firebase functions</h3><p>The package.json file created in functions folder is really important so Firebase can understand <em>cloud functions</em> external dependencies.</p><blockquote><em>Once you deploy Firebase functions, Firebase cloud servers will run </em><em>npm install so the dependencies defined in </em><em>package.json will be installed.</em></blockquote><p>6.1 — First step would be, then moving functions/package.json to dist/package.json.</p><p>6.2 — Take care! The CLI generated .gitignore file would ignore everything inside dist. It would be nice to add this file to your control version system. You can do so with:</p><pre>git add dist/package.json -f</pre><p>6.3 — Remove functions folder</p><h3>7 — Update firebase.json</h3><p>Update firebase.json file like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa523dd9bf34215ce2c7242a97e40d93/href">https://medium.com/media/aa523dd9bf34215ce2c7242a97e40d93/href</a></iframe><p>7.1 — Let’s start with the easy stuff: the functions property. I&#39;ve renamed the folder with <em>cloud functions</em>, so that&#39;s how I tell Firebase to find the new folder. Firebase will upload the whole dist folder to the cloud functions space on every Firebase cloud functions deploy.</p><p>7.2 — Regarding hosting, now files would be stored in dist/browser. But there are a few more details:</p><p>Once you visit the page you want the Express server to respond the request. That’s why you use the rewrites property in hosting section. The glob pattern ** means any route, so any route will be handled by thessr function. That&#39;s the name you will use to export the firebase function wrapping the Express server.</p><blockquote><strong><em>Important:</em></strong><em> </em><em>rewrites rule is only applied when </em><strong><em>no file exists</em></strong><em> in Firebase hosting for the matching route.</em></blockquote><p>You need to take care of that. When the root page URL is visited <strong>you don’t want to serve the index.html static file that exists in </strong><strong>dist/browser</strong>. This file is an empty skeleton. Instead of that, you want to call your Express server to render the whole content of the requested page.</p><p>To bypass this issue, just rename the index.html file that gets generated by npm run build:universal. This way, Firebase won&#39;t find it so it will use ssr function to handle any request to root domain.</p><h3>8 — Renaming index.html to index-1.html</h3><p>8.1 — In order to rename the autogenerated file dist/browser/index.html, you must rename the original file, stored in src folder. So please, <strong>rename </strong><strong>src/index.html to </strong><strong>src/index-1.html</strong>.</p><p>8.2 — There’s one line in your Express server where you define index.htmlas a render entry point. As you have renamed it to index-1.html, you&#39;ll need to update also this server/index.ts code fragment:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d882bff40fd7dabf0c4a9a270b3c0158/href">https://medium.com/media/d882bff40fd7dabf0c4a9a270b3c0158/href</a></iframe><p>8.3 — Finally, you should also update .angular-cli.json file so Angular can find index-1.html and move it to dist/browser folder during the build process. You&#39;ll see that in a moment.</p><h3>9 — Update .angular-cli.json in order to use the new structure</h3><p>9.1 — Open .angular-cli.json and update the index property as well as the outDir of both client and universal apps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23716290fdd94be8aa5279748605c68b/href">https://medium.com/media/23716290fdd94be8aa5279748605c68b/href</a></iframe><p>9.2 — Edit server/tsconfig.ssr.json in order to updated also the output directory of the compiled Express server:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da1ee48ef5968335655170344832425d/href">https://medium.com/media/da1ee48ef5968335655170344832425d/href</a></iframe><h3>10 — Update server to use Firebase</h3><p>Open again the server/index.ts file to make the following changes:</p><p>10.1 — Import firebase:</p><p>10.2 — Find Universal app in the right folder (now dist/server):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c04fb4c9b3bdd0dd58dd1839393d800e/href">https://medium.com/media/c04fb4c9b3bdd0dd58dd1839393d800e/href</a></iframe><p>10.3 — Detect if firebase cloud functions is being used (that would be defined in an environment variable we will define soon):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7fdc9956fe00ce2723a470809220b54/href">https://medium.com/media/c7fdc9956fe00ce2723a470809220b54/href</a></iframe><p>10.4 — Update DIST_FOLDER, as its value will depend on express being used with <em>Firebase functions</em> or not (running npm run serve:universal for example).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a26efcf9009fb45d44792baf9da032d/href">https://medium.com/media/1a26efcf9009fb45d44792baf9da032d/href</a></iframe><p>10.5 — Update paths to follow new structure. Now static files are inside dist/browser (see next step).</p><p>10.6 — <strong>Static files are now served directly by firebase hosting</strong>. Your code that serves static content from Express is only required when DISABLE_FIREBASE is true. Same happens with code running the server (app.listen): Now it is Firebase who launches the server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c28be94bb7532549660b744479fe886e/href">https://medium.com/media/c28be94bb7532549660b744479fe886e/href</a></iframe><p>10.7 — Export Express server as a Firebase function. Remember naming the exported function as ssr.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d310d61273677972f3dc8b5fb113568/href">https://medium.com/media/9d310d61273677972f3dc8b5fb113568/href</a></iframe><h3>11 — Update the serve:universal command</h3><p>As you see, the server is now expecting an environment var DISABLE_FIREBASE (false by default), in order to know if it has to use the Firebase specific code, or the generic Express server approach.</p><p>Update the serve:universal command to set this var to true so you can always run the server without <em>Firebase functions</em>.</p><blockquote><em>Remember that your Express server is compiled in </em><em>dist/index.js.</em></blockquote><p>Update package.json file from root folder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1842ba92e7cd15fc89c1fca4bf79b40/href">https://medium.com/media/b1842ba92e7cd15fc89c1fca4bf79b40/href</a></iframe><p>This way your Universal executions will be faster. Also, using this env var allows you to deploy the same index.ts server in a non-Firebase environment.</p><h3>12 — Install firebase dependencies in your project</h3><p>As you’ll see index.ts file is giving you an error.</p><p>It cannot find firebase-functions package. You need to install it <strong>in the root project </strong>(not in dist). Moreover, you&#39;ll also need to add firebase-admin dependency. From the root project folder, add both dependencies with:</p><pre>npm install firebase-functions firebase-admin --save</pre><h3>13 — Check that it’s still working :)</h3><p>First, without Firebase functions. Simply check that nothing has got broken.</p><p>Compile the whole code with:</p><pre>npm run build:universal</pre><p>and run it with:</p><pre>npm run serve:universal</pre><p>If you’ve followed all the steps, your app should be working fine. Hooray!</p><p>Now let’s see if it is also working locally with Firebase. Run:</p><pre>firebase serve</pre><p>This would run a local server emulating firebase hosting (usually at <a href="http://localhost:5000/">http://localhost:5000</a>) and a local endpoint linked to your <em>firebase function</em>.</p><p>If you go to the hosting URL, the web page should be rendered as expected. Moreover, you should also see in the terminal that the ssr method has been fired.</p><p>Remember to check, also, that the source code your browser has received is the SSR one, instead of an empty template(&lt;app-root&gt;&lt;/app-root&gt;). It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*0GprkUDqBZva0qEp." /></figure><p>So far so good?</p><p>GREAT!</p><p>Now, let’s upload it to Firebase!</p><h3>14 — Add Universal dependencies to Firebase package.json</h3><p>You have included the Firebase package.json file in dist folder. This file includes the dependencies required by Firebase functions. Of course, you also need to include the Universal project dependencies.</p><p>Update dist/package.json dependencies section, so it looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f0080e6ddd767d36f9cd3ec2cecd508/href">https://medium.com/media/0f0080e6ddd767d36f9cd3ec2cecd508/href</a></iframe><blockquote><strong><em>IMPORTANT</em></strong><em>: If your </em><em>dist/package.json file includes the line </em><em>&quot;main&quot;: &quot;lib/index.js&quot;,, remove it.</em></blockquote><h3>15 — Deploy to Firebase</h3><p>Uploading hosting and functions stuff to Firebase is only 1 command away. Run:</p><pre>firebase deploy</pre><p>That’s all!!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GNmSgswQoMWH0wBl." /><figcaption>Photo by <a href="https://unsplash.com/@rayhennessy?utm_source=medium&amp;utm_medium=referral">Ray Hennessy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It would take some time, but at the end, you should receive a “success” message, as well as the link to your Firebase served app.</p><p>As always, make sure that Firebase is working fine and you are getting the SSR page.</p><blockquote>Do you want to access the source code?<a href="https://github.com/kaikcreator/universal-firebase-starter">https://github.com/kaikcreator/universal-firebase-starter</a></blockquote><h3>Personal thoughts</h3><p>Its been a long article, so I am asking myself… have you reached the end?</p><p>YES?</p><p><strong>Then, let me know!!</strong> → I’ll be <strong>really happy to know it</strong> ;)</p><p>Back to my thoughts…</p><p>I’m quite a fan of Angular Universal. It allows you to reduce load time as well as provide SEO features to your Angular website. And with tools like Firebase you don’t even need to be a backend expert to use it!!!</p><p>And Firebase… ok, maybe you can feel conditioned by their environment and I would not recommend it to build custom solutions for big clients.</p><p>However, I think it has a great potential for startups: It drastically reduces costs and development / system maintenance times. <strong>It is a must for personal projects that have some <em>backend</em> requirements.</strong></p><p>What about you? What do you think?</p><p><em>Do you like the article? Then share it!</em> ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c85a7d00862" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/angular-5-universal-firebase-4c85a7d00862">Angular 5 Universal + Firebase</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Service — Component communication]]></title>
            <link>https://medium.com/@enriqueoriol/angular-service-component-communication-4933782af52c?source=rss-97e2a8b4454------2</link>
            <guid isPermaLink="false">https://medium.com/p/4933782af52c</guid>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[angular-4]]></category>
            <category><![CDATA[components]]></category>
            <dc:creator><![CDATA[Enrique oriol]]></dc:creator>
            <pubDate>Wed, 08 Nov 2017 12:55:42 GMT</pubDate>
            <atom:updated>2017-11-08T12:55:42.406Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular good practices recommends you to avoid any logic inside components that it’s not directly related with the view. You should move all that logic to services.</p><p>Working with services that already exist (like HttpClient) is cool and easy. But your feelings may change when you have to create your own services.</p><p>At a first glance, it looks easy. Soon you’ll realize that in order to share data from a service to the component, you’ll need to understand a little bit about <a href="http://reactivex.io/rxjs/">RxJS</a>. This is because reactive programming is highly promoted by Angular. <strong>Observables are the perfect companion for services.</strong></p><p>The problem rises here: There are lot of chances that, the logic you want to move to the service is emitting some kind of output event (EventEmitter).</p><p>However EventEmitter was not designed for services! Ideally, your service API should expose an <a href="http://reactivex.io/rxjs/manual/overview.html#observable">Observable</a> so it can emit the event. That way you will be able to subscribe from the component.</p><h3>Understanding the problem</h3><p>To help you understand the issue, let me show you a basic example: I’ve a really simple timer component that performs a countdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*6XBswU810C7yF7y4incH8g.png" /></figure><p>The countdown component have a input called init with the number of seconds, and an output onComplete that notifies when the countdown has finished.</p><p>It works like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac02f0609ba0df093c1c3c5a4714e4be/href">https://medium.com/media/ac02f0609ba0df093c1c3c5a4714e4be/href</a></iframe><p>I moved the timer logic to a service, <strong>but I still need to emit this </strong><strong>onComplete event someway</strong>. Right now my component looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed701ab8d239794f6c0f5abe557a10fc/href">https://medium.com/media/ed701ab8d239794f6c0f5abe557a10fc/href</a></iframe><p>On the other side, my service is also really simple, only containing the timer logic. Let me show you its structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfe202bba320158c487ac9f2162f426e/href">https://medium.com/media/cfe202bba320158c487ac9f2162f426e/href</a></iframe><p>As you can see, there’s a method that checks if the countdown has finished (processCountdown). I want to emit my event there.</p><p>It seems clear that if the service has an Observable, you will be able to subscribe to it from the component. This way, when the countdown ends you can emit an event from the service. The component can detect then the event and use the EventEmitter as expected.</p><h3>How can I generate Observable events?</h3><p><a href="http://reactivex.io/rxjs/manual/overview.html#subject"><strong>Subject</strong></a> class is key, here.</p><p>Subjects are Observables that can also manage multiple subscriptions to one single flow and even emit events.</p><p>As you only want to create the events internally, you should create a <strong>private </strong><strong>Subject</strong> and then expose the generated flow through a <strong>public </strong><strong>Observable</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de80f1a8e7cdb0a9d4181af39c713476/href">https://medium.com/media/de80f1a8e7cdb0a9d4181af39c713476/href</a></iframe><p>In order to emit a new value through the Observable, you should use the Subject method next().</p><p>That’s exactly what I’m doing in method processCountdown of my service, when the countdown ends:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7a0cf0e19a7aaeefe2bb7fd00047ee9/href">https://medium.com/media/b7a0cf0e19a7aaeefe2bb7fd00047ee9/href</a></iframe><h3>Subscribing to an observable</h3><p>The next steps are <em>easy peasy</em>. From the component you only need to subscribe to that observable and take action when an event is received.</p><blockquote><strong><em>Do not forget cancelling the subscription when component is destroyed.</em></strong><em> In order to do that, you’ll need to hold a reference to the </em><em>Subscription.</em></blockquote><p>My component now looks like that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e82938dbb2c3a4d48758b2c2cf04a1ba/href">https://medium.com/media/e82938dbb2c3a4d48758b2c2cf04a1ba/href</a></iframe><h3>Reactive programming</h3><p>Until now, in the template I’m using the countdown by accessing the property timer.countdown.</p><p>This is not really efficient, as Angular has to check if the countdown value has changed all the time.</p><p>Wouldn&#39;t it be better that the service itself tells the template to update the value? That&#39;s what we know as <strong>Reactive Programming</strong>.</p><blockquote><em>Observables combine specially well with the Angular </em><strong><em>ChangeDetectionPush</em></strong><em> strategy, that reduces the amount of checks Angular performs on runtime.</em></blockquote><blockquote><em>That said, this is a topic to talk about another day ;)</em></blockquote><p>I can follow the previous approach to expose another Observable on the service containing the countdown value. The component will only need to subscribe to that observable.</p><p>A new problem arises here. Until now I had a permanent state and I could check the countdown value anytime. Now, using a Subject to update the counter, I would only be able to get the countdown value at the very moment of receiving the event.</p><p>There’s an easy solution, however. <strong>RxJS</strong> provides a Subject variation that handles those situations, it is known as BehaviorSubject.</p><h3>Subject VS BehaviorSubject</h3><p><a href="http://reactivex.io/rxjs/manual/overview.html#behaviorsubject">BehaviorSubject</a> is like a Subject except that it always has knowledge of it state.</p><p>The main differences of BehaviorSubject, are those:</p><ul><li>It always have a value (you’ll need to initialize it on instantiation).</li><li>At the moment you subscribe, you get the last available value.</li><li>You can always get the value, using the method getValue()</li></ul><h3>Using BehaviourSubject in a service</h3><p>Let me show you how to replace the countdown property of the service (the one that holds the countdown state) by a BehaviorSubject.</p><p>First things first, you need to create a BehaviorSubject and expose its Observable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/083ee2dd42de0a5a1a79e954dd242584/href">https://medium.com/media/083ee2dd42de0a5a1a79e954dd242584/href</a></iframe><p>As you can see, when BehaviorSubject is created, you have to set the initial value.</p><p>Let’s go now with restartCountdown method. In the past, I updated the initial value using this.countdown = this.init. Now, instead of that, I have to do it with the next() method, like this: this.countdownSource.next(this.init).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f77ebde28b51c4c136c6f814364d29d6/href">https://medium.com/media/f77ebde28b51c4c136c6f814364d29d6/href</a></iframe><p>I also have to update the doCountdown method to get and decrement the countdown, using getValue:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bad2b56a7808f94b56ca4f1921749aa/href">https://medium.com/media/9bad2b56a7808f94b56ca4f1921749aa/href</a></iframe><p>I also update processCountdown to get the countdown value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6dea1fba28058dd7002b514a47ea933a/href">https://medium.com/media/6dea1fba28058dd7002b514a47ea933a/href</a></iframe><p>Ready! Now you only need to update the component.</p><p>You could subscribe to the Observable as seen before, to assign the result to a new property and then use it from the template.</p><p>However, you can do something much better: Let’s delegate all this stuff into a pipe.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3osxYaDlxLcexsQiKk%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fdominosuk-pizza-feelings-dominos-3osxYaDlxLcexsQiKk&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3osxYaDlxLcexsQiKk%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="217" frameborder="0" scrolling="no"><a href="https://medium.com/media/487629da98989485d717b18f0b794002/href">https://medium.com/media/487629da98989485d717b18f0b794002/href</a></iframe><h3>AsyncPipe</h3><p><a href="https://angular.io/docs/ts/latest/api/common/index/AsyncPipe-pipe.html"><strong>AsyncPipe</strong></a> is a powerful Angular tool that helps you deal with reactive stuff.</p><p>That pipe subscribes to an Observable, returning the last emitted value. Also, when the component is destroyed, the pipe cancels the subscription for you.</p><p>This way, the only change you need to use this reactive counter is at a template level.</p><p>Look how I’m using the pipe in the time input binding of &lt;app-display&gt;:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa530b852793923d5f4d7d00e799da0a/href">https://medium.com/media/fa530b852793923d5f4d7d00e799da0a/href</a></iframe><p>And that’s all folks!</p><h4><em>You will find this and other good practices in my course </em><a href="https://www.udemy.com/angular-components-like-a-pro/?couponCode=BLOGREADER">Angular Components — like a Pro!</a></h4><p><a href="https://www.udemy.com/angular-components-like-a-pro/?couponCode=BLOGREADER">Angular Components - like a Pro! (angular 2 &amp; 4)</a></p><p>With those changes I forced my component to use the countdown in a completely reactive way, so Angular doesn’t need to check the countdown property all the time.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fc862b2dAhJXYA%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fc862b2dAhJXYA&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fc862b2dAhJXYA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="184" frameborder="0" scrolling="no"><a href="https://medium.com/media/9117d8ab662e5f51126f11f28c6d46cb/href">https://medium.com/media/9117d8ab662e5f51126f11f28c6d46cb/href</a></iframe><p>Wanna <strong>play with the code </strong>from the example? You got it <a href="https://github.com/kaikcreator/simpleTimerDemo">in this repo</a>.</p><h3>To sum up</h3><p>It is highly recommended to move business logic from component to services. This will improve the readability of your code and simplify its testability. Moreover, as you see Angular use powerful tools such as RxJS that will help you apply reactive programming, that is also a good practice.</p><p>Believe me, when you app grows up, you’ll appreciate having followed this approach. Having a good performance might depend on it.</p><blockquote><em>Do you liked this article? Help me spread the word then ;)</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4933782af52c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular with Web Workers: Step by step]]></title>
            <link>https://medium.com/angular-in-depth/angular-with-web-workers-step-by-step-dc11d5872135?source=rss-97e2a8b4454------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc11d5872135</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular2]]></category>
            <dc:creator><![CDATA[Enrique oriol]]></dc:creator>
            <pubDate>Thu, 06 Apr 2017 07:55:58 GMT</pubDate>
            <atom:updated>2017-04-06T07:55:58.113Z</atom:updated>
            <content:encoded><![CDATA[<p>This article describes, step by step, how to modify an existing Angular CLI generated app so it can take advantage of the Angular WebWorkers and run all the business logic inside an isolated thread.</p><h3>Preconditions</h3><p>I’m assuming that you have an Angular project (version 2 or 4) generated with Angular CLI 1.0 or higher. If that’s not the case and you want to practice the content of this article, check <a href="https://github.com/kaikcreator/angular-cli-web-worker">this sample repo</a>.</p><h3>Extract webpack file</h3><p>Since Angular CLI v1.0, there’s the “eject” feature, that allows you to extract the webpack config file and manipulate it as you wish.</p><ol><li>Run ng eject so Angular CLI generates the <em>webpack.config.js</em> file.</li><li>Run npm install so the new dependencies generated by CLI are satisfied</li></ol><h3>Install <em>webworker</em> bootstrap dependencies</h3><p>Run npm install --save @angular/platform-webworker @angular/platform-webworker-dynamic</p><h3>Changes in UI thread bootstrap</h3><h4>Changes in <strong>app.module.ts</strong></h4><p>Replace BrowserModule by WorkerAppModule in the <strong>app.module.ts</strong> file. You’ll also need to update the import statement in order to use @angular/platform-webworker library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21479689fb427a7b95253bc06cc81c6b/href">https://medium.com/media/21479689fb427a7b95253bc06cc81c6b/href</a></iframe><h4>Changes in <strong>src/main.ts</strong></h4><p>Replace bootstrap process with:<strong> </strong>bootstrapWorkerUI (update also the import).</p><p>You’ll need to pass a URL with the file where the web worker is defined. Use a file called webworker.bundle.js, don’t worry, we will create this file soon.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/041cdd599c2177047da52da3682b0f78/href">https://medium.com/media/041cdd599c2177047da52da3682b0f78/href</a></iframe><h4>Create <strong>workerLoader.ts</strong> file</h4><ol><li>Create a new file <strong>src/workerLoader.ts</strong></li><li>As your Web Worker will be a single file containing all the required stuff, you need to include<strong><em> </em></strong>polyfills.ts, @angular/core,<strong><em> </em></strong>and<strong><em> </em></strong>@angular/common packages. On next steps, you will update Webpack in order to transpile and build a bundle with the result.</li><li>Import platformWorkerAppDynamic</li><li>Import the AppModule (remove the import from <strong>main.ts</strong>) and bootstrap it using this platformWorkerAppDynamic platform.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce5f4b26221f8c4495e3d689a9bd929c/href">https://medium.com/media/ce5f4b26221f8c4495e3d689a9bd929c/href</a></iframe><h3>Update webpack to build your webworker</h3><p>The webpack auto generated config file is quite long, but you’ll just need to center your attention in the following things:</p><ol><li>Add a webworker<strong>entry point</strong> for our workerLoader.ts file. If you look at the <em>output</em>, you’ll see that it attaches a <em>bundle.js</em> prefix to all chunks. That’s why during bootstrap step we have used webworker.bundle.js</li><li>Go to <strong>HtmlWebpackPlugin</strong> and exclude the webworker<strong> </strong>entry point, so the generated Web Worker file is not included in the index.html file.</li><li>Go to <strong>CommonChunksPlugin</strong>, and for the inline common chunk, set the entry chunks explicitely to prevent webworker to be included.</li><li>Go to <strong>AotPlugin</strong> and set explicitely the entryModule</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/590fff2338ea3d5c71af479df6c92de9/href">https://medium.com/media/590fff2338ea3d5c71af479df6c92de9/href</a></iframe><h3>You’re ready</h3><p>If you have followed correctly the previous steps, now you only need to compile the code and try the results.</p><p>Run npm start</p><p>All the logic of your Angular app should be running inside a WebWorker, causing the UI to be more fluent.</p><h3>Furter notes</h3><p>npm start runs the <strong>webpack-dev server</strong>, and it has some kind of problem with webworkers throwing an error message on console log. Anyway, the webworker seems to run fine.</p><p>If you compile the app using webpack command and serve it from any http server like <a href="https://www.npmjs.com/package/simplehttpserver">simplehttpserver</a>, the error goes away ;)</p><h3>That’s all folks!</h3><p>If you have enjoyed this post, please share it ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc11d5872135" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angular-in-depth/angular-with-web-workers-step-by-step-dc11d5872135">Angular with Web Workers: Step by step</a> was originally published in <a href="https://medium.com/angular-in-depth">Angular In Depth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>