CSS and PWAs: Some Tips for Building Progressive Web Apps

In recent years we’ve seen a number of major shifts in the online experience, mostly coming from the proliferation of mobile devices. The evolution of the Web has taken us from single versions of a website, to desktop versus mobile versions, to responsive sites that adapt according to screen size, then to native mobile apps, which either recreate the desktop experience as a native app, or act as a gateway to the responsive version.
The latest iteration of all of this is the progressive web app (PWA). A PWA is a software platform that aims to combine the best of both the Web and the native experience for website/app users.
In this article on CSS and PWAs, we’re going to discuss a number of techniques that can be used when creating the CSS required for the development of PWAs.
What are PWAs?
There are three main features of a PWA. As you’ll see, what makes a web app progressive is the “fixing” of problems typically associated with web apps, by adopting some of the techniques used by native apps to resolve these issues.

Reliable. A PWA should reliably load like a native app (no matter the state of the network). This is contrary to a web page, which typically does not load if the device is disconnected from the network.

Fast. The performance of a PWA should be independent of such things as geography, network speed, load or other factors that are beyond the control of the end user.

Engaging. PWAs should mimic the native app’s immersive, full-screen experience without requiring the need of an app store, even supporting such features as push notifications.

There are other features PWA features, but for now, we’ll keep to the most important ones described above.
Google has been at the forefront of pushing these kind of apps, but the adoption of PWAs has been picking up with vendors and plenty of other companies on the Web helping the adoption and embracing the concept of PWAs.
The following are comments from Itai Sadan, CEO of Duda, who was present at Cloudfest 2018:

Progressive web apps represent the next great leap in the evolution of web design and online presence management … they take the best aspects of native apps, such as a feature-rich experience and the ability to be accessed offline, and incorporate them into responsive websites. This creates an incredible web experience for users without the need to download anything onto their device.
Anyone providing web design services to clients is going to want to offer PWAs because over time, just like with mobile and responsive web design, it will become the industry standard.

What is Required for Developing PWAs?
Developing a PWA is not different from developing a standard web application, and it may be possible to upgrade your existing codebase. Note that for deployment, HTTPS is a requirement, although you can do testing on the localhost. The requirements for an app to become a PWA are discussed below.
1. Create a Manifest File
PWAs must be available to install directly via a website which has been visited, meaning there’s no need for a third-party app store to get the app installed.
To enable this, the app needs to provide a manifest.json file — a JSON file that allows the developer to control how the PWA appears, what needs to be launched and other parameters.
A typical manifest file appears below. As we can see, the properties are setting a number of look-and-feel settings that will be used on the home screen of the device where the app will be installed.

The styling of the PWA starts from the manifest file, but there’s no real CSS involved in this part. It’s just straight up properties, which define the application’s name, icons, primary colors, etc.
2. Using a Service Worker
A service worker is essentially a specific type of web worker, implemented as a JavaScript file that runs independently of the browser — such that it’s able to intercept network requests, caching or retrieving resources from the cache, and delivering push messages as necessary.
The service worker is what makes the PWA truly offline capable.
3. Install the Site Assets, Including CSS
The first time the Service worker is registered, an install event is triggered. This is where all of the site assets are installed, including any CSS, JS and other media and resource files required by the application:
self.addEventListener(‘install’, function(e) {
return cache.addAll([

Developing PWAs is not very different from developing web apps, as long as the fundamental requirements have been met.
This is where the CSS starts to get involved, with the files defined that will be used to style the progressive web app.
The post CSS and PWAs: Some Tips for Building Progressive Web Apps appeared first on SitePoint.

Link: https://www.sitepoint.com/pwa-css-considerations/

10 Essential TypeScript Tips and Tricks for Angular Devs

In this article, we’ll dive into a set of tips and tricks that should come in handy in every Angular project and beyond when dealing with TypeScript.
In recent years, the need for static typing in JavaScript has increased rapidly. Growing front-end projects, more complex services, and elaborate command-line utilities have boosted the need for more defensive programming in the JavaScript world. Furthermore, the burden of compiling an application before actually running it hasn’t seen as a weakness, but rather as an opportunity. While two strong parties (TypeScript and Flow) have emerged, a lot of trends actually indicate that only one may prevail — TypeScript.
Besides the marketing claims and commonly known properties, TypeScript has an amazing community with very active contributors. It also has one of the best teams in terms of language design behind it. Led by Anders Hejlsberg, the team has managed to fully transform the landscape of large-scale JavaScript projects to be nearly an exclusively TypeScript-powered business. With very successful projects such as VSTS or Visual Studio Code, Microsoft themselves is a strong believer in this technology.
But it’s not only the features of TypeScript that make the language appealing, but also the possibilities and frameworks that TypeScript is powering. Google’s decision to fully embrace TypeScript as their language of choice for Angular 2+ has proven to be a win-win. Not only did TypeScript gain more attention, but also Angular itself. Using static typing, the compiler can already give us informative warnings and useful explanations of why our code will not work.
TypeScript Tip 1: Supply Your Own Module Definitions
TypeScript is a superset of JavaScript. As such, every existing npm package can be utilized. While the TypeScript eco-system is huge, not all libraries are yet delivered with appropriate typings. Even worse, for some (smaller) packages not even separate declarations (in the form of @types/{package}) exist. At this point, we have two options:

bring in legacy code using TypeScript tip 7
define the API of the module ourselves.

The latter is definitely preferred. Not only do we have to look at the documentation of the module anyway, but typing it out will prevent simple mistakes during development. Furthermore, if we’re really satisfied with the typings that we just created, we can always submit them to @types for including them on npm. As such, this also rewards us with respect and gratefulness from the community. Nice!
What’s the easiest way to supply our own module definitions? Just create a module.d.ts in the source directory (or it could also be named like the package — for example, unknown-module.d.ts for an npm package unknown-module).
Let’s supply a sample definition for this module:
declare module ‘unknown-module’ {
const unknownModule: any;
export = unknownModule;

Obviously, this is just the first step, as we shouldn’t use any at all. (There are many reasons for this. TypeScript tip 5 shows how to avoid it.) However, it’s sufficient to teach TypeScript about the module and prevent compilation errors such as “unknown module ‘unknown-module’”. The export notation here is meant for the classic module.exports = … kind of packages.
Here’s the potential consumption in TypeScript of such a module:
import * as unknownModule from ‘unknown-module’;

As already mentioned, the whole module definition is now placed in the type declaration of the exported constant. If the exported content is a function, the declaration could look like this:
declare module ‘unknown-module’ {
interface UnknownModuleFunction {
(): void;
const unknownModule: UnknownModuleFunction;
export = unknownModule;

Of course, it’s also possible to use packages that export functionality using the ES6 module syntax:
declare module ‘unknown-module’ {
interface UnknownModuleFunction {
(): void;
const unknownModule: UnknownModuleFunction;
export const constantA: number;
export const constantB: string;
export default unknownModule;

TypeScript Tip 2: Enum vs Const Enum
TypeScript introduced the concept of enumerations to JavaScript, which did represent a collection of constants. The difference between
const Foo = {
A: 1,
B: 2,

enum Foo {
A = 1,
B = 2,

is not only of syntactical nature in TypeScript. While both will be compiled to an object (i.e., the first one will just stay as is, while the latter will be transformed by TypeScript), the TypeScript enum is protected and contains only constant members. As such, it would not be possible to define its values during runtime. Also, changes of these values will not be permitted by the TypeScript compiler.
This is also reflected in the signature. The latter has a constant signature, which is similar to
interface EnumFoo {
A: 1;
B: 2;

while the object is generalized:
interface ConstFoo {
A: number;
B: number;

Thus we wouldn’t see the values of these “constants” in our IDE. What does const enum now give us? First, let’s look at the syntax:
const enum Foo {
A = 1,
B = 2,

This is actually the same — but note, there’s a const in front. This little keyword makes a giant difference. Why? Because under these circumstances, TypeScript won’t compile anything. So we have the following cascade:

objects are untouched, but generate an implicit generalized shape declaration (interface)
enum will generate some boilerplate object-initializer along with a specialized shape declaration
const enum doesn’t generate anything beside a specialized shape declaration.

Now how is the latter then used in the code? By simple replacements. Consider this code:
enum Foo {
A = 1,
B = 2

const enum Bar {
A = 1,
B = 2

console.log(Bar.A, Foo.B);

Here we end up in JavaScript with the following outcome:
var Foo;
(function (Foo) {
Foo[Foo[“A"] = 1] = "A";
Foo[Foo["B"] = 2] = "B";
})(Foo || (Foo = {}));
console.log(1 /* A */, Foo.B);

Note that 5 lines alone have been generated for enum Foo, while enum Bar only resulted in a simple replacement (constant injection). Thus const enum is a compile-time only feature, while the original enum is a runtime + compile-time feature. Most projects will be well suited for const enum, but there may be cases where enum is preferred.
Continue reading %10 Essential TypeScript Tips and Tricks for Angular Devs%

Link: https://www.sitepoint.com/10-essential-typescript-tips-tricks-angular/

Using Angular Augury to Debug Your Code

Augury is an open-source tool allowing developers to profile and debug Angular 2 and 4 applications.
Modern web browsers provide developer consoles to inspect various elements on the page, which is really handy when trying to debug markup, styles, and scripts. However, this console isn’t enough to debug Angular applications that usually have lots of components, events, attributes, and a separate routing system.
Augury is a tool designed specifically for Angular apps. It’s an open-source debugging and profiling tool for Angular 2+ applications.
Augury is just a Chrome extension that’s quite simple to use, so you won’t need to spend hours and hours learning how to utilize this tool. We’re going to build a sample Angular app and then see Augury in action by exploring various parts of our project. So, let’s get started!
Hello, Augury!
Augury visualizes your app’s structure in a form of a tree, showing how components and their dependencies relate to each other. It also allows you to inspect properties of your objects and change them on the fly. On top of that, you can easily view the source code of a specific component, insert breakpoints as needed, work with events, and more. Lastly, you can browse the application’s routing system, as well as view the full list of all utilized modules.
Augury is only available as a Chrome extension (there’s no Firefox support yet, unfortunately) and installing it is as simple as going to this page and pressing the Install button. After that, you may open the developer tools by pressing Ctrl + Shift + I (Windows/Linux) or Cmd + Opt + I (macOS). You’ll note that a new tab called Augury has appeared. After switching to this tab, you’ll either see the application’s structure or the phrase “This application is not an Angular application”. I’ve noticed that sometimes it may be required to re-open the Developer Console in order for Augury to analyze the page properly, so watch out.
Now that we have Augury installed, let’s proceed to the next section and prepare the sample application that we’ll use as a playground!
Building a Sample App
In order to see Augury in action, we need something to debug, right? In this section, I’m going to quickly guide you through the process of creating a very simple application (loosely based on the sample app from the Angular’s official tutorial) listing some users and allowing you to edit them. Alternatively, you may grab the source code from my GitHub repo.
Before getting started, install Angular CLI on your machine if you don’t have it yet:
npm install -g @angular/cli

Next, create the skeleton of our new project:
ng new sitepoint-augury

Change the application’s title by tweaking the src/app/app.component.ts file:
// …

export class AppComponent {
title = ‘Augury Demo’;

Tweak the src/app/app.component.html by removing all the links to documentation added automatically by code generator and add an </app-users> line:
<div style=”text-align:center">
Welcome to {{ title }}!


Of course, we need a User component, so generate it now by running:
ng generate component users

Change the src/app/users/user.component.ts file in the following way:
import { Component, OnInit } from ‘@angular/core’;
import { User } from ‘./user.model’; // <— 1
import { UserService } from ‘./user.service’; // <— 2

selector: ‘app-users’,
templateUrl: ‘./users.component.html’,
styleUrls: [‘./users.component.css’]
export class UsersComponent implements OnInit {
users: User[];

selectedUser: User;

onSelect(user: User): void { // <— 3
this.selectedUser = user;

constructor(private userService: UserService) { } // <— 4

ngOnInit() {
this.getUsers(); // <— 5

getUsers(): void { // <— 6
this.users = this.userService.getUsers();


Main things to note here:

We are importing a User model that will be created in a moment.
We’re also importing a UserService. It will simply return a list of hardcoded users, but let’s pretend they’re being fetched from some remote location.
We’re allowing the users to be selected by clicking on them. The currently selected user is stored in a separate selectedUser attribute.
Hook up the userService using the dependency injection mechanism.
Load the list of users once the component is initialized.
In order to get users, we’re utilizing our userService.

That’s pretty much it for this component.
Next, let’s create a model in a src/app/users/user.model.ts file. Each user is going to have an ID, a first and a last name:
export class User {
id: number;
first: string;
last: string;

Nothing complex.
Now let’s proceed to the UserService that’s going to be defined in the app/src/users/user.service.ts file:
import { Injectable } from ‘@angular/core’;
import { User } from ‘./user.model’;

export class UserService {

constructor() { }

getUsers(): User[] {
return [
id: 1,
first: ‘John’,
last: ‘Doe’
id: 2,
first: ‘Margaret’,
last: ‘Brown’

The getUsers method simply returns an array of users with hardcoded data.
Now let’s display our users with the help of ngFor. Also, we’re going to add a click event listener and fire onSelect whenever a user is clicked on. When this happens, a form to edit the chosen user should be displayed (which is going to be done with the help of ngIf). Modify the src/app/users/user.component.html file like this:
<div *ngFor="let user of users" (click)="onSelect(user)"
[class.selected]="user === selectedUser">
<p>, (ID: )</p>

<div *ngIf="selectedUser">
<label for="first">First</label>
<input [(ngModel)]="selectedUser.first" placeholder="First name" id="first">

<label for="last">Last</label>
<input [(ngModel)]="selectedUser.last" placeholder="Last name" id="last">

We’re assigning a .selected CSS class to the chosen user, so let’s add some simple styling for it inside the src/app/users/user.component.css file:
.selected {
font-weight: bold;

Lastly, we have to import FormsModule and UserService inside the src/app/app.module.ts file:
import { BrowserModule } from ‘@angular/platform-browser’;
import { NgModule } from ‘@angular/core’;
import { FormsModule } from ‘@angular/forms’; // <—
import { UserService } from ‘./users/user.service’; // <—

import { AppComponent } from ‘./app.component’;
import { UsersComponent } from ‘./users/users.component’;

FormsModule should be listed in the imports section in the app.module.ts, whereas UserService goes to the providers:
declarations: [
imports: [
FormsModule // <—
providers: [
UserService // <—
bootstrap: [AppComponent]

That’s it! Our sample application is finished, and you can open it by running the following command:
ng serve –open

Continue reading %Using Angular Augury to Debug Your Code%

Link: https://www.sitepoint.com/angular-augury-debug-code/

Boosting Your Workflow with Angular 5 Snippets and VS Code

In this article, we’ll focus on how to use Angular 5 snippets in Visual Studio Code to improve our workflow. We’ll first start with the basics of using and creating snippets. We’ll look at how we can use Angular snippets for VS Code in an Angular project. Then we’ll later look at how we can create our own snippets and share them with others.
For anyone who’s become proficient in a programming language, you know how boring it is to type the same code over and over again. You eventually start copying and pasting pieces of your code to spare your fingers the agony of writing another for loop.
What if your editor could help you insert this common code for you automatically as you type? That would be awesome, right?
Well, you probably know them as snippets. It’s a feature that’s common in every modern IDE currently available. Even Notepad++ supports them (though not enabled by default).
Before you start, you’ll need to have the latest version of Visual Studio Code installed on your machine. We’ll also be looking at Angular 5 snippets. So having at least a basic knowledge of Angular will be helpful, but not necessary.
You’ll need to use an existing or new Angular 5 project in order to experiment with snippets. I assume you have the latest version of Node.js, or at least a version that’s not older than Node.js 6. Here’s the command for installing the Angular CLI tool if you haven’t:
npm install -g @angular/cli

# or
yarn global add @angular/cli

Snippets Explained
Snippets are templates that allow you to easily insert repetitive code. When you first install VSCode, it comes with snippets for JavaScript pre-installed. To check them out, just open an existing JavaScript file or create a new one in your workspace and try out typing these prefixes:


As you type, a popup list will appear giving you options to autocomplete your code. As soon as the right snippet is highlighted, just press enter to insert the snippet. In some cases, such as log and for, you may need to press the down key to select the right snippet.
You’re probably wondering where these JavaScript snippets are coming from exactly. Well, you can find the exact definitions in these locations:

Windows – C:\Program Files\Microsoft VS Code\resources\app\extensions\javascript\snippets\javascript.json
Linux -/usr/share/code/resources/app/extensions/javascript/snippets/javascript.json

We’ll look into how we can create our own snippets, but first let’s explore some third-party snippets.
How to Use Snippets
At the time of writing, the Visual Studio Marketplace listed 934 extensions in the snippet category. You’ll find snippets for every programming language created, including Pascal! This means you probably should check out the marketplace before creating your own snippets. As mentioned earlier, we’ll be looking at Angular 5 snippets. Locate an existing Angular 5 project in your workspace or just create a new one:
ng new snippets-demo

Once the project is set up, open it in VSCode. Next, click the extension icon on the activity bar to open the Extensions panel. Search for Angular 5. The search results should list several Angular extensions. Install the one that has the author ‘John Papa’. After installation is done, click the reload button to restart VSCode. This Angular 5 snippets extension comes with over 50 snippets. About 70% of the snippets are written for TypeScript, and the rest are mostly for HTML. There are some Docker snippets in there too.

Let’s try a few of these Angular 5 snippets. Create a new file called app.service.ts inside the app folder. Open the file and start typing “a-service”. A pop-up list will appear as you type. Even before you finish typing, you should have the correct option highlighted. Press enter to insert the template. Once the snippet is entered, take note that the generated class name is highlighted for you to change.

Just type “App” and the entire class name will read “AppService”. Pretty convenient, right? Let’s try something different. Delete the entire code in app-service.ts and type this prefix:

You should get a service class definition, including imports and HttpClient injection in the class constructor. Just like before, rename the class name to AppService.

Next, let’s use another snippet to define an HTTP GET request. Let’s define an empty GET method. For this piece of code, you have to type; don’t copy-paste:
getPosts(): Observable {


As you start to type “Observable”, a snippet option for it will appear. Just press enter and the Observable class will be imported for you automatically.

Next, let’s use another snippet to complete the function. Start typing this prefix: “a-httpclient-get”. Pressing enter will insert this snippet for you:
return this.httpClient.get(‘url’);

Change the URL to an imaginary path — let’s say /posts. Obviously our code won’t run, as we haven’t set up any APIs. Fix it by adding <any> after get. The complete method now looks like this.
getPosts(): Observable<any[]> {
return this.httpClient.get<any[]>(‘/posts’);

Now that we know a little bit about how to use Angular 5 snippets, let’s see how they’re created.
Continue reading %Boosting Your Workflow with Angular 5 Snippets and VS Code%

Link: https://www.sitepoint.com/boosting-workflow-angular-5-snippets-vs-code/

Top Angular Plugins for Sublime Text

This article covers a number of Angular plugins for the Sublime Text text editor.
Whether you’re new to Angular (version 2+) development, and looking to get started with it and integrate it more closely with your code editor of choice, or you’re an old hand at Angular development and you’re trying your hand with Sublime Text as a new editor, integrating the two has never been easier.
There are lots of options for Angular plugins that can smooth your way developing Angular apps using Sublime Text. You’ll need to set up the Sublime Text package manager (called “Package Control”) prior to getting started, and then you can take a look at the list of plugins here and see if any meet your needs!
Setting up Package Control
In order to use most of the Angular plugins that will be discussed in this article, you’ll first need to set up Package Control in Sublime Text. This is a fairly painless process. The easiest way involves copy-pasting a configuration code.

Use the hotkey CTRL + ` or use the View > Show Console menu to bring up the integrated Sublime Text console.
Paste the block of Python code into the console, which can be copied from the Package Control Installation page and follow the instructions there.
Once this is done, the Package Control menus will be set up! Now, all you’ll need to do is find and install your packages.

Installing a Sublime Text Package via Package Control Menus
Using Package Control is a breeze. You’ll need to open Package Control, select the install menu, and then choose and install a package:

Use the shortcut CMD + Shift + P (CTRL + Shift + P, depending on OS) to open the command palette.
Type install package and then press Enter, which brings you to the list of available packages.
Search for the package by name, select the package, then press Enter to install.

Angular 2 HTML Package
The Angular 2 HTML plugin provides augmented HTML syntax for Sublime Text. You’ll be able to use Angular attributes without syntax highlighting being broken. Additionally, the JavaScript parts of your pages will also highlight as JavaScript. A small but incredibly useful addition for Angular developers.
Angular 2 HTML Package Setup
At the time of this writing, this plugin was not present in Package Control, but can be installed manually via the following steps.

Close Sublime Text and navigate via the Command Line to your Sublime Text 3 “Packages” folder in your application installation. In macOS, this is at /Users/{user}/Library/Application Support/Sublime Text 3/Packages.

Clone the repository into your Packages folder with the following:
git clone https://github.com/princemaple/ngx-html-syntax

Re-open Sublime Text 3, and check in the View > Syntax menu to ensure that Ngx HTML is an option.

Additionally, you can have Sublime Text automatically highlight .component.html files with Angular 2 HTML Syntax:

Open a .component.html file.

Choose View > Syntax > Ngx HTML.

Go to Preferences > Settings > Syntax Specific. Because your current file is using the Ngx HTML syntax, it should open the syntax-specific settings file for Ngx HTML. If so, add an extensions entry to the settings panel on the right:

Restart Sublime Text. Now, all .component.html files should automatically use the Ngx Syntax plugin!

Continue reading %Top Angular Plugins for Sublime Text%

Link: https://www.sitepoint.com/top-angular-plugins-sublime-text/

Authenticating Firebase and Angular with Auth0: Part 2

This article was originally published on the Auth0.com blog, and is republished here with permission.
In this two-part tutorial series, we’ll learn how to build an application that secures a Node back end and an Angular front end with Auth0 authentication. Our server and app will also authenticate a Firebase Cloud Firestore database with custom tokens so that users can leave realtime comments in a secure manner after logging in with Auth0. The Angular application code can be found at the angular-firebase GitHub repo and the Node API can be found in the firebase-auth0-nodeserver repo.
The first part of our tutorial, Authenticating Firebase and Angular with Auth0: Part 1, covered:

intro and setup for Auth0 and Firebase
implementing a secure Node API that mints custom Firebase tokens and provides data for our app
Angular application architecture with modules and lazy loading
Angular authentication with Auth0 with service and route guard
shared Angular components and API service.

Authenticating Firebase and Angular with Auth0: Part 2
Part 2 of our tutorial will cover:

Displaying Dogs: Async and NgIfElse
Dog Details with Route Parameters
Comment Model Class
Firebase Cloud Firestore and Rules
Comments Component
Comment Form Component
Realtime Comments

Our completed app will look something like this:

Let’s pick up right where we left off at the end of Authenticating Firebase and Angular with Auth0: Part 1.
Displaying Dogs: Async and NgIfElse
Let’s implement the home page of our app — the dogs listing. We created the scaffolding for this component when we set up our Angular app’s architecture.
Important Note: Make sure your Node.js API is running. If you need a refresher on the API, refer to How to Authenticate Firebase and Angular with Auth0: Part 1 – Node API.
Dogs Component Class
Open the dogs.component.ts class file now and implement this code:
// src/app/dogs/dogs/dogs.component.ts
import { Component, OnInit } from ‘@angular/core’;
import { Title } from ‘@angular/platform-browser’;
import { ApiService } from ‘../../core/api.service’;
import { Dog } from ‘./../../core/dog’;
import { Observable } from ‘rxjs/Observable’;
import { tap, catchError } from ‘rxjs/operators’;

selector: ‘app-dogs’,
templateUrl: ‘./dogs.component.html’
export class DogsComponent implements OnInit {
pageTitle = ‘Popular Dogs’;
dogsList$: Observable;
loading = true;
error: boolean;

private title: Title,
private api: ApiService
) {
this.dogsList$ = api.getDogs$().pipe(
tap(val => this._onNext(val)),
catchError((err, caught) => this._onError(err, caught))

ngOnInit() {

private _onNext(val: Dog[]) {
this.loading = false;

private _onError(err, caught): Observable<any> {
this.loading = false;
this.error = true;
return Observable.throw(‘An error occurred fetching dogs data.’);


After our imports, we’ll set up some local properties:

pageTitle: to set our page’s <h1> and <title>
dogsList$: the observable returned by our API HTTP request to fetch the dogs listing data
loading: to show a loading icon while the API request is being made
error: to display an error if something goes wrong fetching data from the API.

We’re going to be using the declarative async pipe to respond to the dogsList$ observable returned by our API GET request. With the async pipe, we don’t need to subscribe or unsubscribe in our DogsComponent class: the subscription process will be managed automatically! We just need to set up our observable.
We’ll make Title and ApiService available to our class by passing them to the constructor, and then set up our dogsList$ observable. We’ll use RxJS operators tap (previously known as the do operator) and catchError to call handler functions. The tap operator executes side effects but does not affect the emitted data, so it’s ideal for setting other properties. The _onNext() function will set loading to false (since data has been successfully emitted). The _onError() function will set loading and error appropriately and throw an error. As mentioned before, we don’t need to subscribe or unsubscribe from the dogsList$ observable because the async pipe (which we’ll add in the template) will handle that for us.
On initialization of our component, we’ll use ngOnInit() to spy on the OnInit lifecycle hook to set the document <title>.
That’s it for our Dogs component class!
Dogs Component Template
Let’s move on to the template at dogs.component.html:
<!– src/app/dogs/dogs/dogs.component.html –>
<h1 class=”text-center">{{ pageTitle }}</h1>

<ng-template #noDogs>
<app-loading *ngIf="loading"></app-loading>
<app-error *ngIf="error"></app-error>

<div *ngIf="dogsList$ | async as dogsList; else noDogs">
<p class="lead">
These were the top <a href="http://www.akc.org/content/news/articles/the-labrador-retriever-wins-top-breed-for-the-26th-year-in-a-row/">10 most popular dog breeds in the United States in 2016</a>, ranked by the American Kennel Club (AKC).
<div class="row mb-3">
<div *ngFor="let dog of dogsList" class="col-xs-12 col-sm-6 col-md-4">
<div class="card my-2">
<img class="card-img-top" [src]="dog.image" [alt]="dog.breed">
<div class="card-body">
<h5 class="card-title">#{{ dog.rank }}: {{ dog.breed }}</h5>
<p class="text-right mb-0">
<a class="btn btn-primary" [routerLink]="[‘/dog’, dog.rank]">Learn more</a>


There are a couple things in this template that we’ll take a closer look at:

<ng-template #noDogs>
<app-loading *ngIf="loading"></app-loading>
<app-error *ngIf="error"></app-error>

<div *ngIf="dogsList$ | async as dogsList; else noDogs">

<div *ngFor="let dog of dogsList" …>

This code does some very useful things declaratively. Let’s explore.
First we have an <ng-template> element with a template reference variable (#noDogs). The <ng-template> element is never rendered directly. It’s intended to be used with structural directives (such as NgIf). In this case, we’ve created an embedded view with <ng-template #noDogs> which contains both the loading and error components. Each of these components will render based on a condition. The noDogs embedded view itself will not render unless instructed to.
So how (and when) do we tell this view to render?
The next <div *ngIf="… is actually an NgIfElse using the asterisk prefix as syntactic sugar. We’re also using the async pipe with our dogsList$ observable and setting a variable so we can reference the stream’s emitted values in our template (as dogsList). If something goes wrong with the dogsList$ observable, we have an else noDogs statement that tells the template to render the <ng-template #noDogs> view. This would be true before the data has been successfully fetched from the API, or if an error was thrown by the observable.
If dogsList$ | async has successfully emitted a value, the div will render and we can iterate over our dogsList value (which is expected to be an array of Dogs, as specified in our component class) using the NgForOf (*ngFor) structural directive to display each dog’s information.
As you can see in the remaining HTML, each dog will be displayed with a picture, rank, breed, and a link to their individual detail page, which we’ll create next.
View the Dogs component in the browser by navigating to your app’s homepage at http://localhost:4200. The Angular app should make a request to the API to fetch the list of dogs and display them!
Note: We’ve also included the <app-comments> component. Since we’ve generated this component but haven’t implemented its functionality yet, it should show up in the UI as text that says “Comments works!”
To test error handling, you can stop the API server (Ctrl+c in the server’s command prompt or terminal). Then try reloading the page. The error component should display since the API cannot be reached, and we should see the appropriate errors in the browser console:

Continue reading %Authenticating Firebase and Angular with Auth0: Part 2%

Link: https://www.sitepoint.com/authenticating-firebase-angular-auth0-2/

Creating UIs with Angular Material Design Components

In this tutorial, I’ll introduce you to Material Design in Angular, then we’ll look at how to create a simple Angular application with a UI built from various Angular Material components.
The widespread adoption of component-based frameworks such as Angular, React and Vue.js has seen a growing number of pre-built UI component collections become available. Using such collections can help developers to quickly create professional-looking applications.
What’s Material Design?
Material Design (codenamed Quantum Paper) is a visual language that can be used to create digital experiences. It’s a set of principles and guidelines across platforms and devices for interactivity, motion and components that simplify the design workflow for teams designing their product.
The Material components allow you to create professional UIs with powerful modularity, theming and customization features.
Introduction to Angular Material
Angular Material is the implementation of Material Design principles and guidelines for Angular. It contains various UI components, such as:

form controls (input, select, checkbox, date picker and sliders etc.),
navigation patterns (menus, sidenav and toolbar)
layout components (grids, cards, tabs and lists )
indicators (progress bars and spinners)
popups and modals
data tables with headers and pagination etc.

Before you can continue with this tutorial, you need to make sure you have a development machine with Node (6.9.0+) and NPM (3+) installed.
You also need to have the Angular CLI installed. If that’s not the case, simply run the following command in your terminal or command prompt:
npm install -g @angular/cli

Create the Project with the Angular CLI
Let’s now create the Angular project using the Angular CLI. Simply run the following command:
ng new angularmaterialdemo

You can then serve your application by running:
cd angularmaterialdemo
ng serve

The application will be running at http://localhost:4200.
Since we’re going to demonstrate different Angular Material components, we need to create a few Angular components and routing configurations for a simple demo application, so go ahead and use the CLI to generate the components:
ng g component login
ng g component CustomerList
ng g component CustomerCreate

Next, open src/app/app.module.ts and add the router configuration:

import { RouterModule, Routes } from ‘@angular/router’;


const appRoutes: Routes = [
{ path: ‘customer-list’, component: CustomerListComponent },
{ path: ‘customer-create’, component: CustomerCreateComponent },
path: ‘login’,
component: LoginComponent
{ path: ”,

redirectTo: ‘/login’,

pathMatch: ‘full’


Getting Started with Angular Material
Now that we have a basic application, let’s get started by installing Angular Material and its different dependencies to enable the different features such as gestures and animations.
Installing Angular Material and Angular CDK
Let’s start by installing Angular Material and Angular CDK from npm.
Head back to your terminal and run the following command:
npm install –save @angular/material @angular/cdk

Adding HammerJS for Gestures Support
Components such as mat-slide-toggle, mat-slider and matTooltip require the HammerJS library for gestures support, so you need to install it for getting the full features of these components. Simply run the following command in your terminal:
npm install –save hammerjs

Next, open src/main.js (the entry point of your application) and import hammerjs
import ‘hammerjs’;

Adding a Theme
Angular Material has a bunch of pre-built themes. To use a theme, you simply need to import it in styles.css:
@import “~@angular/material/prebuilt-themes/indigo-pink.css";

You can find more information about theming in this guide.
Adding Angular Material Icons
Angular Material comes with a mat-icon component for icons, so you need to load the icon font before you can use it.
Add the following tag to your index.html file:

Using Animations with Angular Material Components
The last thing is enabling animations. Some components rely on the Angular animations module for advanced transitions, so you need to install the @angular/animations module and include the BrowserAnimationsModule in your application module configuration.
First, head back to your terminal and run the following command:
npm install –save @angular/animations

Next, open src/app/app.module.ts and add the following code:
/* … */
import {BrowserAnimationsModule} from ‘@angular/platform-browser/animations’;

imports: [
export class AppModule { }

Importing Angular Material Components
Before you can use any Angular Material component, you’ll have to import its module. Each component has its own module so you can include only the components you’re going to use.
Another approach is to create a separate module and import all the Angular Material components you need to use and then simply include this module in your application module.
So go ahead and create a src/app/material.module.ts file, and then add the following content:
import { NgModule } from ‘@angular/core’;
import {MatNativeDateModule,MatSnackBarModule,MatIconModule,MatDialogModule, MatButtonModule, MatTableModule, MatPaginatorModule , MatSortModule,MatTabsModule, MatCheckboxModule, MatToolbarModule, MatCard, MatCardModule, MatFormField, MatFormFieldModule, MatProgressSpinnerModule, MatInputModule } from ‘@angular/material’;
import {MatDatepickerModule} from ‘@angular/material/datepicker’;
import {MatRadioModule} from ‘@angular/material/radio’;
import {MatSelectModule} from ‘@angular/material/select’;
import {MatSliderModule} from ‘@angular/material/slider’;
import {MatDividerModule} from ‘@angular/material/divider’;

imports: [MatTabsModule,MatDividerModule,MatSliderModule,MatSelectModule,MatRadioModule,MatNativeDateModule,MatDatepickerModule,MatSnackBarModule,MatIconModule,MatDialogModule,MatProgressSpinnerModule,MatButtonModule,MatSortModule,MatTableModule,MatTabsModule, MatCheckboxModule, MatToolbarModule, MatCardModule, MatFormFieldModule, MatProgressSpinnerModule, MatInputModule, MatPaginatorModule],
exports: [MatTabsModule,MatDividerModule,MatSliderModule,MatSelectModule,MatRadioModule,MatNativeDateModule,MatDatepickerModule,MatSnackBarModule,MatIconModule,MatDialogModule,MatProgressSpinnerModule,MatButtonModule,MatSortModule, MatCheckboxModule, MatToolbarModule, MatCardModule,MatTableModule,MatTabsModule, MatFormFieldModule, MatProgressSpinnerModule, MatInputModule, MatPaginatorModule],


export class MyMaterialModule { }

Next, include this module in src/app/app.module.ts:
import { MyMaterialModule } from ‘./material.module’;




imports: [


export class AppModule { }

That’s it: you can now use the imported Angular Material components in your Angular application.
Continue reading %Creating UIs with Angular Material Design Components%

Link: https://www.sitepoint.com/angular-material-design-components/

Authenticating Firebase and Angular with Auth0: Part 1

This article was originally published on the Auth0.com blog, and is republished here with permission.
In this 2-part tutorial series, we’ll learn how to build an application that secures a Node back end and an Angular front end with Auth0 authentication. Our server and app will also authenticate a Firebase Cloud Firestore database with custom tokens so that users can leave realtime comments in a secure manner after logging in with Auth0.
The Angular application code can be found at the angular-firebase GitHub repo and the Node API can be found in the firebase-auth0-nodeserver repo.
Authenticating Firebase and Angular with Auth0: Part 1
Part 1 of our tutorial will cover:

Firebase and Auth0
What We’ll Build
Angular CLI
Auth0 Client and API
Firebase Project with Service Account
Node API
Set Up Angular App
Angular App Architecture
Implement Shared Modules
Implement Routing and Lazy Loaded Modules
Loading and Error Components
Authentication Logic
Core Logic
Next Steps

Firebase and Auth0
Firebase is a mobile and web application development platform. Firebase was acquired by Google in 2014, and continues to be developed under the Google umbrella. Firebase provides NoSQL databases (RTDB, or Realtime Database and Cloud Firestore, in beta at the time of writing) hosted in the cloud and connected using web sockets to provide realtime capabilities to apps.
Auth0 is a cloud-based platform that provides authentication and authorization as a service. As an authentication provider, Auth0 enables developers to easily implement and customize login and authorization security for their apps.
Choosing Auth0 + Firebase Authentication
If you’re already familiar with Firebase’s offerings, you might be asking: why would we implement Auth0 with custom tokens in Firebase instead of sticking with Firebase’s built-in authentication by itself?
Firstly, there is an important distinction to make here. Using Auth0 to secure Firebase does not mean you are not using Firebase auth. Firebase has a custom authentication approach that allows developers to integrate their preferred identity solution with Firebase auth. This approach enables developers to implement Firebase auth so that it functions seamlessly with proprietary systems or other authentication providers.
There are many potential reasons we might want to integrate Auth0 with Firebase authentication. Alternatively, there are scenarios where using basic Firebase auth by itself could suffice. Let’s explore.
You can use Firebase’s built-in authentication by itself if you:

Only want to authenticate Firebase RTDB or Firestore and have no need to authenticate additional back ends
Only need a small handful of login options and do not need enterprise identity providers, integration with your own user storage databases, etc.
Do not need extensive user management, profile enrichment, etc. and are comfortable managing users strictly through an API
Have no need to customize authentication flows
Do not need to adhere to compliance regulations regarding the storage of user data.

You should consider Auth0 with a custom Firebase token if you:

Already have Auth0 implemented and want to add realtime capabilities to your app
Need to easily use issued tokens to secure a back end that is not provided by Firebase
Need to integrate social identity providers beyond just Google, Facebook, Twitter, and GitHub
Need to integrate enterprise identity providers, such as Active Directory, LDAP, ADFS, SAMLP, etc.
Need a customized authentication flow
Need robust user management with APIs and an admin-friendly dashboard
Want to be able to dynamically enrich user profiles
Want features like customizable passwordless login, multifactor authentication, breached password security, anomaly detection, etc.
Must adhere to compliance regulations such as HIPAA, GDPR, SOC2, etc.

Essentially, Firebase’s basic authentication providers should suffice if you have a very simple app with bare-bones authentication needs and are only using Firebase databases. However, should you need more than that, Firebase offers a great way to use their services with other authentication solutions. This is a much more realistic scenario that many developers will be faced with, so we’ll explore it in detail here.
What We’ll Build
We’re going to build a Node.js API secured with Auth0 that mints custom Firebase tokens and also returns data on ten different dog breeds.
We’ll also build an Angular front end app called “Popular Dogs” that displays information about the ten most popular dogs in 2016, ranked by public popularity by the American Kennel Club (AKC). Our app will be secured by Auth0, call the Node API to fetch dog data, and call the API to acquire Firebase tokens to authorize users to add and delete comments in realtime with Cloud Firestore. The app will use shared modules as well as implement lazy loading.

To implement the app, you will need the following:

Angular CLI
A free Auth0 account with a Client and an API configured
A free Firebase project with a service account

Let’s get started!
Angular CLI
Make sure you have Node.js with NPM installed on your local machine. Run the following command to install the Angular CLI globally:
$ npm install -g @angular/cli@latest

We will generate our Angular app and nearly all of its architecture using the CLI.
Auth0 Client and API
You’ll need an Auth0 account to manage authentication. You can sign up for a free account here.

Next, set up an Auth0 client app and API so Auth0 can interface with the Angular app and Node API.
Set Up an Auth0 Client

Go to your Auth0 Dashboard and click the Create a New Client button.
Name your new app (something like Angular Firebase) and select Single Page Web Applications.
In the Settings for your new Auth0 client app, add http://localhost:4200/callback to the Allowed Callback URLs.
Enable the toggle for Use Auth0 instead of the IdP to do Single Sign On.
At the bottom of the Settings section, click “Show Advanced Settings". Choose the OAuth tab and verify that the JsonWebToken Signature Algorithm is set to “RS256”.
If you’d like, you can set up some social connections. You can then enable them for your app in the Client options under the Connections tab. The example shown in the screenshot above uses username/password database, Facebook, Google, and Twitter.

Note: For production, make sure you set up your own social keys and do not leave social connections set to use Auth0 dev keys.
Set Up an Auth0 API

Go to APIs in your Auth0 dashboard and click on the “Create API” button. Enter a name for the API, such as Firebase Dogs API. Set the Identifier to your API endpoint URL. In this tutorial, our API identifier is http://localhost:1337/. The Signing Algorithm should be “RS256”.
You can consult the Node.js example under the Quick Start tab in your new API’s settings. In the next steps, we’ll implement our Node API in this fashion using Express, express-jwt, and jwks-rsa.

We’re now ready to implement Auth0 authentication on both our Angular client and Node back-end API.
Firebase Project with Service Account
Next you will need a free Firebase project.
Create a Firebase Project

Go to the Firebase Console and sign in with your Google account.
Click on Add Project.
In the dialog that pops up, give your project a name (such as Angular Firebase Auth0). A project ID will be generated based on the name you chose. You can then select your country/region.
Click the Create Project button.

Generate an Admin SDK Key
In order to mint custom Firebase tokens, you’ll need access to the Firebase Admin SDK. To obtain access, you must create a service account in your new Firebase project.
Click on the gear wheel icon next to your Project Overview in the Firebase console sidebar and select Project Settings from the menu that appears:

In the settings view, click the Service Accounts tab. The Firebase Admin SDK UI will appear, showing a configuration code snippet. Node.js is selected by default. This is the technology we want, and we will implement it in our Node API. Click on the Generate New Private Key button.
A dialog will appear warning you to store your private key confidentially. We will take care never to check this key into a public repository. Click on the Generate Key button to download the key as a .json file. We will add this file to our Node API shortly.
Node API
The completed Node.js API for this tutorial can be found at the firebase-auth0-nodeserver GitHub repo. Let’s learn how to build this API.
Node API File Structure
We’ll want to set up the following file structure:

You can generate the necessary folders and files with the command line like so:
$ mkdir firebase-auth0-nodeserver
$ cd firebase-auth0-nodeserver
$ mkdir firebase
$ touch firebase/.gitignore
$ touch .gitignore
$ touch config.js
$ touch dogs.json
$ touch package.json
$ touch routes.js
$ touch server.js

Firebase Admin SDK Key and Git Ignore
Now move the Firebase Admin SDK .json key file you downloaded earlier into the firebase folder. We will take care to make sure the folder is checked in, but its contents are never pushed to a repo using the firebase/.gitignore like so:
# firebase/.gitignore

This .gitignore configuration ensures that Git will ignore any files and folders inside the firebase directory except for the .gitignore file itself. This allows us to commit an (essentially) empty folder. Our .json Firebase Admin SDK key can live in this folder and we won’t have to worry about gitignoring it by filename.
Note: This is particularly useful if we have the project pulled down on multiple machines and have different keys (with different filenames) generated.
Next let’s add the code for the root directory’s .gitignore:
# .gitignore

Dogs JSON Data
Next we’ll add the data for ten dog breeds. For brevity, you can simply copy and paste this data into your dogs.json file.
Let’s add our package.json file like so:
"name": "firebase-auth0-nodeserver",
"version": "0.1.0",
"description": "Node.js server that authenticates with an Auth0 access token and returns a Firebase auth token.",
"repository": "https://github.com/auth0-blog/firebase-auth0-nodeserver",
"main": "server.js",
"scripts": {
"start": "node server"
"author": "Auth0",
"license": "MIT",
"dependencies": {},
"devDependencies": {}

We’ll install the dependencies with the command line and latest versions will be saved automatically to the package.json file:
$ npm install –save body-parser cors express express-jwt jwks-rsa firebase-admin

We’ll need body-parser, cors, and express to serve our API endpoints. Authentication will rely on express-jwt and jwks-rsa, while Firebase token minting is implemented with the firebase-admin SDK (which we’ll have access to using the key we generated).
In the config.js file, add the following code and replace the placeholder values with your own settings:
// config.js
module.exports = {
AUTH0_DOMAIN: ‘<Auth0 Domain>’, // e.g., you.auth0.com
AUTH0_API_AUDIENCE: ‘<Auth0 API Audience>’, // e.g., http://localhost:1337/
FIREBASE_KEY: ‘./firebase/<Firebase JSON>’, // e.g., your-project-firebase-adminsdk-xxxxx-xxxxxxxxxx.json
FIREBASE_DB: ‘<Firebase Database URL>’ // e.g., https://your-project.firebaseio.com

With our data, configuration, and dependencies in place, we can now implement our Node server. Open the server.js file and add:
// server.js
// Modules
const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const cors = require(‘cors’);

// App
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

// Set port
const port = process.env.PORT || ‘1337’;
app.set(‘port’, port);

// Routes

// Server
app.listen(port, () => console.log(`Server running on localhost:${port}`));

This will launch our Node server with Express at http://localhost:1337/.
Note: Notice that this is the API identifier we set up in Auth0.
API Routes
Next open the routes.js file. This is where we’ll define our API endpoints, secure them, and mint custom Firebase tokens. Add the following code:
// routes.js
// Dependencies
const jwt = require(‘express-jwt’);
const jwks = require(‘jwks-rsa’);
const firebaseAdmin = require(‘firebase-admin’);
// Config
const config = require(‘./config’);

module.exports = function(app) {
// Auth0 athentication middleware
const jwtCheck = jwt({
secret: jwks.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${config.AUTH0_DOMAIN}/.well-known/jwks.json`
audience: config.AUTH0_API_AUDIENCE,
issuer: `https://${config.AUTH0_DOMAIN}/`,
algorithm: ‘RS256’

// Initialize Firebase Admin with service account
const serviceAccount = require(config.FIREBASE_KEY);
credential: firebaseAdmin.credential.cert(serviceAccount),
databaseURL: config.FIREBASE_DB

// GET object containing Firebase custom token
app.get(‘/auth/firebase’, jwtCheck, (req, res) => {
// Create UID from authenticated Auth0 user
const uid = req.user.sub;
// Mint token using Firebase Admin SDK
.then(customToken =>
// Response must be an object or Firebase errors
res.json({firebaseToken: customToken})
.catch(err =>
message: ‘Something went wrong acquiring a Firebase token.’,
error: err

// Set up dogs JSON data for API
const dogs = require(‘./dogs.json’);
const getDogsBasic = () => {
const dogsBasicArr = dogs.map(dog => {
return {
rank: dog.rank,
breed: dog.breed,
image: dog.image
return dogsBasicArr;

// GET dogs (public)
app.get(‘/api/dogs’, (req, res) => {

// GET dog details by rank (private)
app.get(‘/api/dog/:rank’, jwtCheck, (req, res) => {
const rank = req.params.rank * 1;
const thisDog = dogs.find(dog => dog.rank === rank);

At a high level, our routes file does the following:

Sets up authentication checking to ensure that only logged in users can access routes with jwtCheck middleware
Initializes the Firebase Admin SDK with the private key generated from the Firebase project service account
Provides a secure GET endpoint that returns a custom Firebase token
Provides a public GET* endpoint that returns a short version of the dogs data
Provides a secure GET* endpoint that returns a specific dog’s detailed data, requested by rank.

*Endpoints use variations of the same base dataset to simulate a more complex API.
You can read the code comments for more detail.
Serve the API
You can serve the Node API by running:
$ node server

The API will then be available at http://localhost:1337.
Note: If you try to access secure routes in the browser, you should receive a 401 Unauthorized error.
That’s it for our server! Keep the API running so that it will be accessible to the Angular app, which we’ll set up next.
Continue reading %Authenticating Firebase and Angular with Auth0: Part 1%

Link: https://www.sitepoint.com/authenticating-firebase-angular-auth0-1/