Category Archives for Angular

How to Build a Serverless Angular App on Azure

Building web applications is hard work. Not only do you have to build the application, you need to figure out where to host it. Ever want to skip all the frustrating server provisioning and focus on your code? If so, then serverless architecture is worth a look. In this article, you will learn how to build setup a serverless Angular app using Azure.

What exactly do you mean by “serverless”?

The term “serverless” is somewhat misleading. There are still servers, but you don’t have to care about them.

Serverless architecture runs on managed services that host your code. Server level concerns like figuring out how much memory you need, fault tolerance, and scalability are abstracted away. You don’t need to pick out a VM or service tier. The service scales automatically. You upload your code and go. The service takes care of the rest.

Serverless platforms come in several different flavors including APIs like Firebase and functions as a service (FAAS). FAAS is where you host small bits of code in the cloud. Think micro-services to the nth degree. All of the major cloud providers have some flavor of FAAS. Examples include: Amazon Lambda, Google Cloud Functions, and Azure Functions. You can even host your own FAAS using OpenFAAS, though that kinda defeats the point. (comprehensive list of serverless platforms)

For the purposes of this application, we are going to use Azure Functions for our backend API.

Where do we put the web site?

While Angular application are complex to develop, they compile into a handful of static files. There’s no reason you can’t throw these files up on any commodity static host. In this case, we’re going to use Azure Web Sites. While this solution isn’t 100% serverless, (you have to pick a hosting tier) hosting a handful of files on the free tier is close enough for me. To add another layer of performance, we’re also going to use Azure CDN to cache the files so they load quickly.

Roadmap

Here’s what we’re going to do:

  • Build an API using Azure Functions
  • Setup an Azure Web App to host our Angular application
  • Setup Azure CDN to serve those files more quickly
  • Add CORS headers on our function app so we can use it with our Angular app
  • Setup a SPA redirect to prevent unintended 404 errors

Building an API with Azure Functions

We start off by creating a new Azure Function app. Starting from the Azure Portal, click “New” search for “function” and click Function App. This will bring you to the new function app blade. Type in your app name (it has to be unique), add the rest of your info and click Create.

Now we’re going to make a function. Either hit the plus sign or click “New Function”. This brings you to the function template screen before. Functions can be activated by a variety of triggers including DB requests, files, and manual activation. We’re going to use the HTTP Trigger. HTTP triggers are activated by an HTTP request. Select “HttpTrigger – C#”.

You should now have this lovely boilerplate. This code can handle any http request and sends back a response.

Let’s ditch that boilerplate and drop in our API code. This is just going to be a simple GET request. Feel free to pretend we’re calling a database here instead of just returning a list.

If you’d like to test your shiny new function, click the “get function url” link and drop that into Postman. As you can see here, things are working splendidly.

You can also test using the built-in testing utility on the right side of the function window.

Setting up an Azure Web Site

Now that we have our backend setup, let’s put together our front end. In this case, we’re going to set up an Angular application built with the Angular CLI. Since this post is about setting up the architecture, I’m not going to go into great detail about the application itself, which can be found in this github repo. If you’re using another front-end library like React or Vue.js, this setup should be mostly the same.

To begin, create an Azure Web App. (New -> Web App). The free tier should be adequate for our needs. We’re just hosting a few files. If you want to use your own custom domain, you’ll need to use a higher tier.

Now we need to get the static files to host. If you’re using Angular CLI (and you should be…), the command to do this is:

ng build --prod --aot

After that command runs, head over to the dist folder of your angular app. It should look something like this:

The next step is to get your static files into the web app. I used FTP, though you can download a publish profile if you want. Drop your static files into the wwwroot folder. At this point, you should be able go to the URL and your app will load.

The next step is to set up a CDN. Since these are just static files, we can use a CDN to serve them. Azure CDN also allow us to serve the site over https without having to pay for a plan that supports SSL. To set one up, go to New, search “CDN”, click “CDN”, and click “Create”.

This brings up the CDN profile blade. Type in your name, select “Standard” for your pricing tier, and select your web site from the dropdown. Then click “Create”. Now you have a CDN for your static files.

Setting up CORS

Now that we have our web app in place, we need to set up the CORS (cross origin resource sharing) headers on our function. Browsers, by default, prevent your website from accessing APIs that don’t match the url of your web application (CORS error pictured below). This feature helps to prevent Cross Site Request Forgery (CSRF) attacks, but is sometimes kind of annoying. If you want to use your function API from your web application, you’ll need to add a CORS header to your API.

To begin, go back to your function app and go to the “Platform features” tab and click “CORS”.

This brings you to the CORS screen. Add the url/s of your web app. You can use “*”, which is the wildcard route, but you shouldn’t because it’s rather insecure. It’s best to use your web app’s URL here.

Setting up a SPA Redirect

At this point, we have a functioning web application, but there’s still one more issue to resolve. Like most SPA applications, Angular supports client side urls that don’t correspond to server-side resources. All of our application code is served from index.html on the root url, but we use the Angular router to map urls to parts of the application. For example, in our sample app, if we navigate from the home page to the Products page it works great, but if we hit refresh we get a 404. (error below) This is because there’s no page on the server for that URL. To fix this we need to add a URL re-write rule to redirect anything that’s not a static asset back to the index page.

To do this, we’re going to create a web.config file with our rewrite rule.

Here’s our rule (finished product):

This rule takes anything that isn’t a file, directory, or an asset (*.html, *.js, *.css) and redirects it to the index page. If you have fonts or images in your application, you should probably add rules for those file extensions as well.

Then, take that web.config file and drop it into the wwwroot folder of our web app. App urls should now redirect appropriately.

Conclusion

If you’d like to build an Angular application and host it for cheap in the cloud, this is a great way to do it. The serverless architecture is great for MVPs, simple applications, and proof of concept applications. It’s an easy way to get code into the world with minimum fuss.

References / Additional Information

If you’d like additional information or access to the code referenced in this post, check out the links below.

Demo Code

Cloud hosting for a static website

Azure Functions Docs

URL Rewrites in an Azure Web App

URL Rewrite Docs

Angular CLI With .NET Core

Angular is a fantastic platform for building rich client side apps, but let’s not forget about the back end. My choice for the back end is ASP.NET Core. If you’re not shy about spending a bunch of time setting up Webpack, Angular and ASP.NET Core is a fantastic combination.

However, I prefer to spend my time building applications, not configuring build tools. Angular CLI takes a lot of the pain out of using Angular, but it’s a self contained command line tool. Fortunately, Angular CLI and ASP.NET Core can happily co-exist. In this post, we’re going to build an application using these two technologies together. By the end, you’ll be ready to have all the goodness of Angular and ASP.NET Core without spending a week setting up Webpack.

Prerequisites

Make sure you have .NET Core, Node.js and Angular CLI installed.

https://www.microsoft.com/net/core#windowsvs2017

https://nodejs.org/en/

npm install -g @angular/cli 

Getting Started: ASP.NET Core App Setup

Fire up Visual Studio (I’m using VS 2017) and create a new ASP.NET Core Web Application. Select the Web API Starter. This doesn’t bring in any web stuff, which is ideal. We’re going to use Angular CLI to generate the client files.

Then go ahead and disable automatic Typescript compilation. We want CLI to compile our Typescript, not Visual Studio. Do this by adding the “TypeScriptCompilerBlocked” line to your csproj file.

Head on over to the Startup.cs and add in the static files middleware. You’ll have to install the “Microsoft.AspNetCore.StaticFiles” NuGet package. After that, add app.UseDefaultFiles() and app.UseStaticFiles() to your Configure() method.

After you get those setup, you’ll want to add some middleware to redirect those pesky 404s to the root file. This will allow you to navigate the application without having to start at the root each time you hit refresh. For this app, api routes are prefixed with “api”, so we’re excluding those routes from the check. We’re also excluding routes with a file extension since those are likely static assets.

To prevent the app from loading up the api/values endpoint by default, go to properties/launchSettings.json and change the “launchUrl” keys from “api/values” to “”.

At this point, our .NET Core app should be ready to go. Let’s move on to the Angular code.

Setting Up Angular CLI

We’re going generate our Angular app on top of our ASP.NET core app. To do this, go to the command line and navigate to the directory of your solution file. Then run “ng new <your app name>”.

You want the <app name> part to be the same as your .NET Core source folder. This will drop all of the CLI files into your ASP.NET Core root folder. It should look like this:

Gluing It All Together

Angular has a default file structure, but it’s not ideal for the existing ASP.NET Core application. Fortunately, Angular CLI has some options that will allow us to change this structure. We want the client side code to be in a folder called “client-src” and the client side build artifacts to go to the wwwroot folder. To do this, rename the “src” folder to “client-src”. Then go to go to .angular-cli.json. This is the primary configuration file for Angular CLI. First, change “src” to “client-src”. Then change the “outDir” attribute from “dist” to “wwwroot”. This will drop all of the compiled assets into the wwwroot folder.

At this point, we can build the Angular application using Angular CLI. Navigate a command prompt into the main application folder and run “ng build”. This command will build the client side part of the application, dropping the build artifacts into wwwroot. The wwwroot folder should look like this:

  

At this point we should be able to run the app by hitting the Run button in Visual Studio. Unfortunately, we still have a two stage build pipeline. The first step being “ng build” to generate the client side files and then running the .NET Core app. To fix this, we can drop in a post build script: “ng build — aot”. This will compile the client side files (with ahead of time compiling) after the app builds.

Bonus Points

If you’re using git, you’ll want to add the wwwroot folder to your .gitignore file. These files are generated, so you probably don’t want to check them in.

Example Code

All of the demo code used in this post is available here:

https://github.com/DustinEwers/shiny-angular-demos/tree/master/ninjas-quest-cli-core/ninjas-quest

This demo includes a full Angular application on top of ASP.NET core. Feel free to use this as a template or something to look at while building your own. You now have everything you need to get started building shiny applications using Angular CLI and ASP.NET Core.

Debugging Angular Apps with Augury

I recently went on a hunt for Angular (formerly known as Angular 2)  profiling tools.  Angular is a fantastic framework, but the component hierarchies can get a little crazy. Fortunately, there’s a way to tame the complexity. After some Google searching, I came across Augury. Augury is a debugging and profiling tool created by Google and Rangle.io.

Augury is simple to install. First, install the Augury Chrome Extension (Sorry Firefox lovers, no soup for you.) There is no step 2.

Once installed, Augury shows up as a new tab in your Chrome Developer Tools. If you have an Angular app running in debug mode (it doesn’t work on prod mode), the tab will show several visualizations of your application. The first one is the component tree, which lays out the components for whatever page you are on. Click a component to see the properties and events for it. You can also manipulate the underlying models and trigger events. Additionally, each component is has a link to its source code. If you want to set a breakpoint, just click and you’ll be right there.

 

You can also get a visualization of injected services by clicking on the Injector Graph. It’ll help you figure out where your dependencies come from.

 

If your application is using routing, click on the routing tree tab to get a visualization of the routing structure.You can click into the routes to see what url triggers them, along with other route information. If you happen to use lazy loading, those routes are marked as “lazy loaded” until you access them.

If you want to see a breakdown of your application’s module structure, click the NgModules tab. This is a good way to get a high level overview of your application.

 

Overall, Augury makes it easier to reason about your Angular applications. By visualizing the component trees, routing, and module structures, you get a high level overview of your application’s structure. Additionally, the extra debugging features add a layer of easy to the already fantastic Chrome Developer tools. I’ve added this to my day-to-day Angular tool belt and urge you to do the same.

More Information

Augury Home

Augury Guide

Cutting Through The JavaScript Toolchain Thicket with Angular CLI

If there is a developer hell, one of the circles will involve the JavaScript toolchain. The JavaScript ecosystem is awash in tools, choices, and configuration options. Combine that with spurious documentation and constant change and you have a jungle of pain awaiting any brave soul who dares build a modern JS application.

Much has been done to ease JavaScript toolchain fatigue. There are templates and starter packs for most of the popular JS stacks. If you’re using Angular 2, the Angular team has created a tool called Angular CLI. It encapsulates all the best practices into one handy command line tool. Angular CLI shortcuts most of the Angular 2 setup. Just run a few commands and you have a working application. In addition to the build tools, you also get a set of scaffolding tools. If you’re familiar with the Ruby on Rails scaffolding tools, Angular CLI will feel right at home. In the interest of trying new things, I decided to kick the tires on Angular CLI and see if it lives up to the hype. I took my demo Angular 2/TypeScript/Webpack application (repo here) and ported it over to Angular CLI.

Installing Angular CLI

npm install -g angular-cli

Install the Angular CLI tool using NPM. Make sure to run the npm install as an administrator. Easy peasy.

Scaffolding an Application

npm install -g angular-cli
ng new <my app name>
cd <my app name>
ng serve

These commands will spin up a basic app structure for you to use. This app structure has a lot of goodies included. Testing, linting, hot module loading, and a decent starter app all come with the basic template. CLI abstracts away the webpack setup, so you don’t have to figure that out. It even includes a basic demo server for you to serve your application from. The only thing that the angular cli doesn’t include is a style library. I’d love to see Angular Material or Bootstrap included with the CLI, but I’ll live.

Here’s what comes out of the box with a new Angular CLI Project:

I was curious about how up to date the basic setup is, so I ran “npm outdated”. NPM packages change often. It looks like most of the packages are close to their most recent version, but the CLI used Angular 2.3 instead of Angular 2.4.

Generators

Boilerplate code sucks and Angular 2 has a bunch of it. There are lots of small files that need be built when you add a new component. Angular CLI has generators to help with that. I tried out a few of the generators. I found the component generator to be particularly useful. It builds out the template, code, and spec files. It also adds the component to its root module. This is a great time saver. The route generator was far less useful, however, as it didn’t do anything. It looks like they’re going to add it back in later.

Styles

The default template doesn’t include any style libraries, so I pulled in Angular Material (currently in beta).

To install:

npm install --save @angular/material

Then you need to pull it into your app module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { CharacterBuilderComponent } from './character-builder/character-builder.component';
import { EncounterComponent } from './encounter/encounter.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { StatsComponent } from './stats/stats.component';
import { HomeComponent } from './home/home.component';
import { MaterialModule } from '@angular/material';
@NgModule({
declarations: [
AppComponent,
CharacterBuilderComponent,
EncounterComponent,
NavMenuComponent,
StatsComponent,
HomeComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MaterialModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Finally, add a theme file to your site.css. There are several pre-built themes, but you can make your own if you want.

@import '~@angular/material/core/theming/prebuilt/deeppurple-amber.css';

After importing the styles I ported all of my demo code over into the angular cli project. This process was surprisingly easy. Unfortunately, the Material styles are not as robust as the Bootstrap styles. I’m sure I made a mistake somewhere, but I wasn’t really going for maximum style, so I let it go. I’m looking forward to Material UI being ready for primetime, but I don’t think it’s quite there yet.

Final Verdict

I wouldn’t use Angular CLI in production (yet), but I think it’s a fantastic tool for playing with and learning Angular 2. It takes the most painful part of setting up an Angular 2 project and makes it a breeze. You can get up and going faster than building an environment from scratch. I’m going to keep an eye on this project and see how it develops. If you build Angular 2 apps, I recommend you do the same.

Here’s the final result:

https://github.com/DustinEwers/typescript-demos/tree/master/ts-demo-node/ninjas-quest

Lazy Loading Modules With Angular 2 And Webpack

I’m sure this is obvious to some people, but this issue threw me for a loop.

When building applications in Angular 2, it’s best practice to divide up your application into feature modules. This keeps your code simple and easy to work with. You can lazy load these child modules to improve initial load times and keep people from downloading code for areas they don’t have access to.

The Angular 2 website has excellent tutorials on how to set this up, but if you’re using Webpack, those instructions (link) don’t quite work.

Here’s the code from the Angular 2 website.

export const routes: Routes = [
  { path: '', redirectTo: 'contact', pathMatch: 'full'},
  { path: 'crisis', loadChildren: 'app/crisis/crisis.module#CrisisModule' },
  { path: 'heroes', loadChildren: 'app/hero/hero.module#HeroModule' }
];

You could assume that this code isn’t specific to using system.js as your module loader, but you’d be wrong. Webpack, by default, chokes on these lazy loaded modules. I spent more time than I’m willing to admit trying to figure out the arcane errors before I realized that the Webpack was the problem. Fortunately, this problem is easy to fix.

Like everything else in Webpack, there’s a loader for that. In this case, you want the Angular 2 Router Loader (more info here). Be attentive to the instructions, because the module strings work different than they do with system.js. For example, the Webpack loader supports relative paths. (The Angular 2 docs say otherwise) Once you setup the loader, lazy loading in Webpack works like a champ.