How to Build a Serverless, CMS-powered Angular Application

Angular has taken off in popularity and is in widespread use. Developed and maintained by Google engineers, Angular has found a place all across dynamic web applications and is an increasingly in-demand platform.
Angular offers the advantages of a large and enthusiastic community and outstanding MVC that doesn’t require developers to spend valuable time writing code to put multiple MVC components back together again. In short, Angular is a robust and comprehensive web application framework for front-end development that is unit-testing ready, making it the tool of choice for many developers.
If you’re using Angular, you may run into the need for content management capability — a blog being one example. Adding a CMS to an Angular app may seem daunting, especially if you’re trying to integrate it into a traditional CMS like WordPress, but there’s a new breed of API-based CMS that greatly simplifies things. ButterCMS is one example of a SaaS-based headless CMS that provides a hosted CMS dashboard and content API that you query from your Angular application. This means you don’t need to spin up any new infrastructure to add a CMS to your Angular app.
This tutorial will demonstrate how to build a CMS-powered Angular application that has marketing pages (customer case studies), a blog, and FAQ, all powered via an API. No servers needed!
Installation
First, you’ll get started by installing the Angular CLI.
npm install -g @angular/cli

Set up a new Angular project using Angular CLI. By default, Angular CLI uses CSS styling, so adding the –style=scss flag tells Angular CLI to use SCSS instead:
ng new hello-buttercms-project –style=scss
cd hello-buttercms-project

Install Angular Material and Angular Material related package:
npm install –save @angular/material @angular/cdk
npm install –save @angular/animations

Install ButterCMS. Run this in your command line:
npm install buttercms –save

Butter can also be loaded using a CDN:
<script src=”https://cdnjs.buttercms.com/buttercms-1.1.1.min.js"></script>

Quickly Get Started
Open the project in your code editor of choice. Under src/app create a directory called _services.
We create a file called butterCMS.service.js. This allows us to have your API Token in one place and not accidentally alter it.
import * as Butter from ‘buttercms’;

export const butterService = Butter(‘b60a008584313ed21803780bc9208557b3b49fbb’);

You’ll import this file into any component we want to use ButterCMS.
For a Quickstart, go to src/app/hello-you/hello-you.component.ts and import butterService:
import {butterService} from ‘../_services’;

Inside the HelloYouComponent create methods:
fetchPosts() {
butter.post.list({
page: 1,
page_size: 10
})
.then((res) => {
console.log(‘Content from ButterCMS’)
console.log(res)
})
}

Now call this method when the component is loaded by adding it to the OnInit lifecycle hook:
ngOnInit() {
this.fetchPosts();
}

This API request fetches your blog posts. Your account comes with one example post, which you’ll see in the response.
Next, create another method to retrieve the Homepage Headline Content Field:
fetchHeadline() {
butter.content.retrieve([‘homepage_headline’])
.then((res) => {
console.log(‘Headline from ButterCMS’)
console.log(res)
})
}

Add this method to the OnInit lifecycle hook.
ngOnInit() {
this.fetchPosts();
this.fetchHeadline();
}

This API request fetches homepage headline content. You can set up your own custom content fields to manage any kind of content you need.
Add Marketing Pages
Setting up CMS-powered pages is a simple, three-step process:

Define the Page Type
Create a page
Integrate into your application

Define Page
First, create a Page Type to represent your Customer Case Study pages. Next, define the fields you want for your customer case studies. With your Page Type defined, you can now create the first case study page. Specify the name and URL of the page, and then populate the content of the page.
With your page defined, the ButterCMS API will return it in JSON format like this:
Continue reading %How to Build a Serverless, CMS-powered Angular Application%

Link: https://www.sitepoint.com/how-to-build-a-serverless-cms-powered-angular-application/

How to Update Angular Projects to the Latest Version

In this article, we’ll look at how to update Angular projects to the latest version.
This article is part 6 of the SitePoint Angular 2+ Tutorial on how to create a CRUD App with the Angular CLI.

Part 0 — The Ultimate Angular CLI Reference Guide
Part 1 — Getting our first version of the Todo application up and running
Part 2 — Creating separate components to display a list of todos and a single todo
Part 3 — Update the Todo service to communicate with a REST API
Part 4 — Use Angular router to resolve data
Part 5 — Add authentication to protect private content
Part 6 — How to Update Angular Projects to the latest version.

In part 1 we learned how to get our Todo application up and running and deploy it to GitHub pages. This worked just fine but, unfortunately, the whole app was crammed into a single component.
In part 2 we examined a more modular component architecture and learned how to break this single component into a structured tree of smaller components that are easier to understand, reuse and maintain.
In part 3 we updated our application to communicate with a REST API backend using RxJS and Angular’s HTTP service.
In part 4, we introduced Angular Router and learned how the router updates our application when the browser URL changes and how we can use the router to resolve data from our backend API.
In part 5, we added authentication to our application and learned how we can protect sections from our application from unauthorized access.
Don’t worry! You don’t need to have followed part 1, 2, 3, 4 or 5 of this tutorial for 6 to make sense. You can simply grab a copy of our repo, check out the code from part 5, and use that as a starting point. This is explained in more detail below.
Up and Running
To start on our goal to update Angular, make sure you have the latest version of the Angular CLI installed. If you don’t, you can install it with the following command:
npm install -g @angular/cli@latest

If you need to remove a previous version of the Angular CLI, you can:
npm uninstall -g @angular/cli angular-cli
npm cache clean
npm install -g @angular/cli@latest

After that, you’ll need a copy of the code from part 5. This is available on GitHub. Each article in this series has a corresponding tag in the repository so you can switch back and forth between the different states of the application.
The code that we ended with in part 5 and that we start with in this article is tagged as part-5. The code that we end this article with is tagged as part-6.
You can think of tags like an alias to a specific commit ID. You can switch between them using git checkout. You can read more on that here.
So, to get up and running (with the latest version of the Angular CLI installed) we would do this:
git clone git@github.com:sitepoint-editors/angular-todo-app.git
cd angular-todo-app
git checkout part-5
npm install
ng serve

Then visit http://localhost:4200/. If all’s well, you should see the working Todo app.
Update Angular: Our Plan of Attack
In this article, as we update Angular, we’ll learn the following:

how Angular versions work
where to find instructions on how to update Angular
how to update our code from Angular 4 to Angular 5 (Angular 5 being the latest version at time of writing).

By the end of this article, you’ll understand:

the underlying meaning of specific Angular versions
where to find exact instructions on how to update Angular applications
how to figure out which code changes are required (if any) for Angular 5.

Let’s get started!
The Meaning of Angular Versions
To support a thriving ecosystem, Angular needs to be both stable and evolutionary.
On one hand, Angular aims to provide developers with maximum stability for mission-critical applications. On the other hand, it constantly needs to adapt and advance to support the latest changes in web technologies.
Therefore, the Angular team has decided to use a time-based release cycle with semantic versioning.
A time-based release cycle means that we can expect new versions of Angular (Angular 5, Angular 6, Angular 7, etc.) every couple of weeks or months.
Semantic versioning means that the version number of Angular allows us to predict whether or not it will break our application if we upgrade to it.
In essence, a semantic version looks like this: Major.Minor.Patch.
So version v1.3.8 has a major component with a value of 1, a minor component with a value of 3 and a patch component with a value of 1.
When a new version is released, the new version implicitly indicates the type of change that was made to the code.
The following rules are applied when a semantic version is increased:

Each increment happens numerically with an increment of 1.

When a bug is fixed and the code stays backwards compatible, the patch component is increased:
v0.0.3 // Before bugfix
v0.0.4 // After bugfix

When functionality is added and the code stays backwards compatible, the minor component is increased and the patch component is reset to zero:
v0.2.4 // Before addition of new functionality
v0.3.0 // After addition of new functionality

When a change is implemented that causes the code to become backwards incompatible, also known as a breaking change, the major component is increased and the minor and patch components are reset to zero:
v7.3.5 // Before implementing backwards incompatible changes
v8.0.0 // After implementing backwards incompatible changes

If you’re not familiar with semantic versioning, make sure to check out this simple guide to semantic versioning.
The Angular team combines semantic versioning with a time-based release cycle to aim at:

a new patch release every week
a new minor release every month
a new major release every 6 months

The release schedule is not set in stone, as there may be holidays or special events, but it’s a good indicator of what we can expect in terms of upcoming versions.
You can follow the official Angular blog and the official change log to stay up to date on the latest developments.
A huge benefit of semantic versions is that we can safely update Angular applications with patch or minor releases without having to worry about breaking our applications.
But what if there’s a new major release?
The Angular Update Guide
We already learned that a major release can come with breaking changes. So how do we know if our existing application will break or not if we update it?
One way would be to read the official change log and go through the list of changes.
A much easier way is to use the Angular Update Guide to update Angular. You select your current version of Angular and the version you wish to upgrade to and the application tells you the exact steps you need to take:

For our Angular Todo application, we wish to upgrade from Angular 4.0 to Angular 5.0.
Let’s select app complexity level Advanced so we see all the possible measures we need to take:

We get a complete overview of all the steps we need to take to update our application.
How sweet is that!
Before Updating
The Before Updating list contains 12 items. None of the items apply to our Angular Todo application, so we can safely proceed to the next step.
During the Update
From the During the Update list, only the last item applies to our application. We need to update our dependencies, so let’s run the proposed commands in the root of our project:
$ npm install @angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}@’^5.0.0′ typescript@2.4.2 rxjs@’^5.5.2′

$ npm install typescript@2.4.2 –save-exact

Because we updated our Angular CLI to the latest version in the Up and Running section, we also update our local version:
$ npm install @angular/cli@latest –save-dev

To verify that our application runs correctly, we run:
$ ng serve

If ng serve fails to start, try deleting your node_modules directory and package-lock.json file and run npm install to recreate a clean node_modules directory and package-lock.json file.
Continue reading %How to Update Angular Projects to the Latest Version%

Link: https://www.sitepoint.com/update-angular-projects/

AngularJS, Basic to Expert: Day Four

Introduction:
In the previous articles of this AngularJS, From Basic to Expert series, we learned what AngularJS is, and looked at some basics of AngularJS, such as directives, the main concepts of AngularJS, which are modules, models, and controllers, and used them in our AngularJS demo application.
You can check previous articles here:

Link: https://dzone.com/articles/angularjs-basic-to-expert-day-four?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

AngularJS and Angular 2+: a Detailed Comparison

This article compares the major differences between the the original AngularJS and Angular 2+. If you’re currently stuck with an AngularJS project and not sure whether you should make the jump, this article should help you get started.
In recent years, we’ve seen Angular grow tremendously as a framework and as a platform for developing single page applications (SPAs) and progressive web apps (PWAs). AngularJS was built on top of the idea that declarative programming should be used for building the views. This required decoupling the DOM manipulation from the business logic of the application and the approach had many benefits on its own.
However, AngularJS had many shortcoming in terms of performance and how things worked under the hood. Hence, the development team spent a year rewriting the code from scratch and finally released Angular 2 in late 2016. Most developers felt that Angular 2 was a different platform that had very little resemblance to the original AngularJS.
So let’s compare and contrast AngularJS and Angular 2+.
Frameworks in AngularJS and Angular 2
AngularJS follows the traditional MVC architecture that comprises a model, a view and a controller.

Controller: the controller represents how user interactions are handled and binds both the model and the view.
Views: the view represents the presentation layer and the actual UI.
Model: the model is an abstract representation of your data.

Some developers are of the opinion that AngularJS follows MVVM pattern that replaces the Controller with a View-Model. A View-Model is a JavaScript function that’s similar to that of the controller. What makes it special is that it synchronizes the data between a view and a model. The changes made to a UI element automatically propagate to the model and vice versa.
The following diagram shows how various AngularJS pieces are connected together.

You can read more about AngularJS’s architecture on the official documentation page.
Angular, on the other, hand has a component-based architecture. Every Angular application has at least one component known as the root component. Each component has an associated class that’s responsible for handling the business logic and a template that represents the view layer. Multiple, closely related components can be stacked together to create a module and each module forms a functional unit on its own.

As you can see in the figure, the component is bound to the template. Components are composed using TypeScript classes and templates are attached to them using @Component annotations. Services can be injected into a component using Angular’s dependency injection subsystem. The concept of modules in Angular is drastically different from that of the AngularJS modules. An NgModule is a container for defining a functional unit. An NgModule can comprise components, services and other functions. The modular unit can then be imported and used with other modules.
All the Angular concepts are better explained at Angular.io.
Templates in AngularJS and Angular 2
In AngularJS the template is written using HTML. To make it dynamic, you can add AngularJS-specific code such as attributes, markups, filters and form controls. In addition, it supports the two-way data binding technique mentioned earlier. The following code snippet demonstrates the use of directives and double curly brackets within the template:

<!– Body tag augmented with ngController directive –>
<body ng-controller=”MyController">
<inpu#t ng-model="foo" value="bar">
<!– Button tag with ngClick directive –>
<!– Curly bracket is a template binding syntax –>
button ng-click="changeFoo()"></button>
<script src="angular.js"></script>
</body>
</html>

In Angular, AngularJS’s template structure was reworked and lots of new features were added to the templates. The primary difference was that each component had a template attached to it. All the HTML elements except <html>, <body>, <base>, and <script> work within the template. Apart from that, there are features such as template binding, template interpolation, template statements, property binding, event binding and two-way binding. Built-in attribute directives like NgClass, NgStyle and NgModel and built-in structural directives such as NgIf, NgForOf, NgSwitch are also part of the template.
Continue reading %AngularJS and Angular 2+: a Detailed Comparison%

Link: https://www.sitepoint.com/angularjs-vs-angular/

Angular Testing: A Developer’s Introduction

In this guide, we’ll look at how we can write automated tests in Angular 5 projects. Angular Testing is a core feature available in every project that was set up with either the Angular CLI or the Angular quick start project.
The subject of Angular testing is vast, as it’s a complex and very involved topic. It would require several chapters or a full-length course to cover it fully. So in this guide, I’ll show you just the basics to get you started.
Prerequisites
At the time of writing, Angular 5.2 is the current stable version — which is what we’ll be using here. This guide assumes you at least have a solid grasp of Angular 4+ fundamentals. It’s also assumed you at least understand the concept or have some skills writing automated tests.
We’ll base our testing examples on Angular’s official beginner tutorial to demonstrate how to write tests for components and services. You can find the completed code with tests on our GitHub repository. At the end of this guide, you should have the skills to implement several passing tests in Angular 5.

Angular Testing Technologies
As you already know, an Angular project is made up of templates, components, services and modules. They all run inside what’s known as the Angular environment. While it’s possible to write isolated tests, you won’t really know how your code will interact with other elements within the Angular environment.
Luckily, we have several technologies that can help us write such unit tests with the least amount of effort.
1. Angular Testing Utilities
This is a set of classes and functions that are needed to build a test environment for Angular code. You can find them on Angular’s api documentation. The most important of all is the TestBed. It’s used to configure an Angular module just the same way as the @NgModule — except that it prepares the module for testing. It has a configureTestingModule function where you provide all the necessary dependencies for your component to function in a test environment. Here’s an example of the dashboard component being prepared to run in a test environment. Several dependencies are needed by this component for the test to run:
TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [ DashboardComponent ],
schemas: [ NO_ERRORS_SCHEMA ],
providers: [
{
provide: HeroService,
useClass: MockHeroService
}
],
})
.compileComponents();

We’ll look more closely at what’s going on here a little further below.
2. Jasmine
Jasmine is the de facto framework for writing Angular tests. Basically, it’s a testing framework that uses the behavior-driven notation. Writing a test in Jasmine is quite simple:
describe(‘createCustomer’ () => {

it(‘should create new customer’,(customer) => {

expect(response).toEqual(newCustomer)
});

it(‘should not create customer with missing fields’, () => {

expect(response.error.message).toEqual(‘missing parameters’)
});

it(‘should not create customer with existing record’, () => {

expect(response.error.message).toEqual(‘record already exists’)
});
});

The anatomy of a Jasmine test is made up of at least two elements: a describe function, which is a suite of tests, and an it function, which is the test itself. We normally use describe to indicate the function we’re focusing on — for example, createCustomer(). Then, within the suite, we create multiple it tests. Each test puts the target function under a different condition in order to ensure it behaves as expected. You can refer to the Jasmine docs for more information.
3. Karma
Karma is a tool for executing source code against test code inside a browser environment. It supports the running of tests in each browser it’s configured for. Results are displayed on both the command line and on the browser for the developer to inspect which tests have passed or failed. Karma also watches the files and can trigger a test rerun whenever a file changes. At the root of the Angular project, we have the file karma.conf that’s used to configure Karma. The contents should look something like this:
module.exports = function (config) {
config.set({
basePath: ”,
frameworks: [‘jasmine’, ‘@angular/cli’],
plugins: [
require(‘karma-jasmine’),
require(‘karma-chrome-launcher’),
require(‘karma-jasmine-html-reporter’),
require(‘karma-coverage-istanbul-reporter’),
require(‘@angular/cli/plugins/karma’)
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: [ ‘html’, ‘lcovonly’ ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: ‘dev’
},
reporters: [‘progress’, ‘kjhtml’],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [‘Chrome’],
singleRun: false
});
};

Do check out Karma’s configuration documentation to learn how to customize it. As you can see, Chrome is listed as the browser to use for running tests. You’ll need to define an environment variable called CHROME_BIN that points to the location of your Chrome browser executable. If you’re using Linux, just add this line to your .bashrc file:
export CHROME_BIN=”/usr/bin/chromium-browser"

In order for Karma to run your tests, you must ensure the test files end with .spec.ts. You should note that Karma was designed to mostly run unit tests. To run end-to-end tests, we’ll need another tool, Protractor, which we’ll look into next.
4. Protractor
Protractor is an end-to-end test framework for Angular. It runs your tests inside a real browser, interacting with it as real person would. Unlike unit tests, where we test individual functions, here we test the entire logic. Protractor is able to fill in forms, click buttons and confirm that the expected data and styling is displayed in the HTML document. Just like Karma, Protractor has its own configuration file at the root of your Angular project, protractor.conf:
const { SpecReporter } = require(‘jasmine-spec-reporter’);

exports.config = {
allScriptsTimeout: 11000,
specs: [
‘./e2e/**/*.e2e-spec.ts’
],
capabilities: {
‘browserName’: ‘chrome’
},
directConnect: true,
baseUrl: ‘http://localhost:4200/’,
framework: ‘jasmine’,
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require(‘ts-node’).register({
project: ‘e2e/tsconfig.e2e.json’
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};

You can find the documentation for its configuration here. Unlike Jasmine/Karma tests, Protractor tests are located outside the src folder, in a folder called e2e. We’ll look into writing end-to-end tests later down the road. For now, let’s start writing unit tests.
Continue reading %Angular Testing: A Developer’s Introduction%

Link: https://www.sitepoint.com/angular-testing-introduction/

AngularJS, Basic to Expert: Day Three

Introduction:
In the previous articles of AngularJS from basic to expert Day One and Day Two, we learned what AngularJS is, and we looked at some basics of AngularJS and AngularJS expressions and directives and used AngularJS in our demo application.
You can check the previous articles here:

Link: https://dzone.com/articles/angularjs-basic-to-expert-day-three?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Angular 2 Authentication: Protecting Private Content

In this article, we’ll add authentication to our Angular application and learn how we can protect sections from our application from unauthorized access.
This article is part 5 of the SitePoint Angular 2+ Tutorial on how to create a CRUD App with the Angular CLI.

Part 0 — The Ultimate Angular CLI Reference Guide
Part 1 — Getting our first version of the Todo application up and running
Part 2 — Creating separate components to display a list of todos and a single todo
Part 3 — Update the Todo service to communicate with a REST API
Part 4 — Use Angular router to resolve data
Part 5 — Add authentication to protect private content

In part 1 we learned how to get our Todo application up and running and deploy it to GitHub pages. This worked just fine but, unfortunately, the whole app was crammed into a single component.
In part 2 we examined a more modular component architecture and learned how to break this single component into a structured tree of smaller components that are easier to understand, reuse and maintain.
In part 3 we updated our application to communicate with a REST API backend using RxJS and Angular’s HTTP service.
In part 4, we introduced Angular Router and learned how the router updates our application when the browser URL changes and how we can use the router to resolve data from our backend API.
Don’t worry! You don’t need to have followed part 1, 2, 3 or 4 of this tutorial, for five to make sense. You can simply grab a copy of our repo, check out the code from part 4, and use that as a starting point. This is explained in more detail below.
Up and Running
Make sure you have the latest version of the Angular CLI installed. If you don’t, you can install it with the following command:
npm install -g @angular/cli@latest

If you need to remove a previous version of the Angular CLI, you can run this:
npm uninstall -g @angular/cli angular-cli
npm cache clean
npm install -g @angular/cli@latest

After that, you’ll need a copy of the code from part 4. This is available at https://github.com/sitepoint-editors/angular-todo-app. Each article in this series has a corresponding tag in the repository so you can switch back and forth between the different states of the application.
The code that we ended with in part 4 and that we start with in this article is tagged as part-4. The code that we end this article with is tagged as part-5.
You can think of tags like an alias to a specific commit id. You can switch between them using git checkout. You can read more on that here.
So, to get up and running (with the latest version of the Angular CLI installed) we would do this:
git clone git@github.com:sitepoint-editors/angular-todo-app.git
cd angular-todo-app
git checkout part-4
npm install
ng serve

Then visit http://localhost:4200/. If all’s well, you should see the working Todo app.
Plan of Attack
In this article, we will:

set up a backend to authenticate against
add a sign-in method to our existing ApiService
set up an authentication service to handle authentication logic
set up a session service to store session data
create a SignInComponent to display a sign-in form
set up a route guard to protect parts of our application from unauthorized access.

By the end of this article, you’ll understand:

the difference between cookies and tokens
how to create an AuthService to implement authentication logic
how to create a SessionService to store session data
how to create a sign-in form using an Angular reactive form
how to create a route guard to prevent unauthorized access to parts of your application
how to send a user’s token as an Authorization Header in an HTTP request to your API
why you should never send your user’s token to a third party.

Our application will look like this:

So, let’s get started!
Authentication Strategy
Server-side web applications typically handle user sessions on the server. They store session details on the server and send the session ID to the browser via a cookie. The browser stores the cookie and automatically sends it to the server with every request. The server then grabs the session ID from the cookie and looks up the corresponding session details from its internal storage (memory, database, etc). The session details remain on the server and are not available in the client.
In contrast, client-side web applications, such as Angular applications, typically manage user sessions in the client. The session data is stored in the client and sent to server when needed. A standardized way to store sessions in the client are JSON Web Tokens, also called JWT tokens. If you’re unfamiliar with how tokens work, check out this simple metaphor to easily understand and remember how token-based authentication works and you’ll never forget again.
If you want to get a deeper understanding of cookies and tokens, make sure to check out Philippe De Ryck’s talk on Cookies versus tokens: a paradoxial choice.
Due to the popularity of JSON Web Tokens in today’s ecosystem, we’ll use a JWT-based authentication strategy.
Setting Up the Backend
Before we can add authentication to our Angular application, we need a back end to authenticate against.
In the previous parts of this series, we use json-server to serve back end data based on the db.json file in the root of our project.
Luckily, json-server can also be loaded as a node module, allowing us to add custom request handlers.
Let’s start by installing the body-parser npm module, which we’ll need to parse the JSON in our HTTP requests:
$ npm install –save body-parser

Next, we create a new file json-server.js in the root of our project:
const jsonServer = require(‘json-server’);
const server = jsonServer.create();
const router = jsonServer.router(‘db.json’);
const middlewares = jsonServer.defaults();
const bodyParser = require(‘body-parser’);

// Sample JWT token for demo purposes
const jwtToken = ‘eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiU2l0ZVBvaW50IFJ’ +
‘lYWRlciJ9.sS4aPcmnYfm3PQlTtH14az9CGjWkjnsDyG_1ats4yYg’;

// Use default middlewares (CORS, static, etc)
server.use(middlewares);

// Make sure JSON bodies are parsed correctly
server.use(bodyParser.json());

// Handle sign-in requests
server.post(‘/sign-in’, (req, res) => {
const username = req.body.username;
const password = req.body.password;
if(username === ‘demo’ && password === ‘demo’) {
res.json({
name: ‘SitePoint Reader’,
token: jwtToken
});
}
res.send(422, ‘Invalid username and password’);
});

// Protect other routes
server.use((req, res, next) => {
if (isAuthorized(req)) {
console.log(‘Access granted’);
next();
} else {
console.log(‘Access denied, invalid JWT’);
res.sendStatus(401);
}
});

// API routes
server.use(router);

// Start server
server.listen(3000, () => {
console.log(‘JSON Server is running’);
});

// Check whether request is allowed
function isAuthorized(req) {
let bearer = req.get(‘Authorization’);
if (bearer === ‘Bearer ‘ + jwtToken) {
return true;
}
return false;
}

This article is not meant to be a tutorial on json-server, but let’s quickly have a look at what’s happening.
First we import all json-server machinery:
const jsonServer = require(‘json-server’);
const server = jsonServer.create();
const router = jsonServer.router(‘db.json’);
const middlewares = jsonServer.defaults();
const bodyParser = require(‘body-parser’);

In a real-world application, we would dynamically generate a JWT token when a user authenticates, but for the purpose of this demo, we define a JWT token statically:
// Sample JWT token for demo purposes
const jwtToken = ‘eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiU2l0ZVBvaW50IFJ’ +
‘lYWRlciJ9.sS4aPcmnYfm3PQlTtH14az9CGjWkjnsDyG_1ats4yYg’;

Next, we configure json-server to run its own default middlewares:
// Use default middlewares (CORS, static, etc)
server.use(middlewares);

and to parse incoming JSON requests properly:
// Make sure JSON bodies are parsed correctly
server.use(bodyParser.json());

Json-server’s default middlewares are request handler functions that deal with static files, CORS, etc. For more detailed information, check out the documentation.
We then define a request handler for sign-in requests:
// Handle sign-in requests
server.post(‘/sign-in’, (req, res) => {
const username = req.body.username;
const password = req.body.password;
if(username === ‘demo’ && password === ‘demo’) {
res.json({
name: ‘SitePoint Reader’,
token: jwtToken
});
}
res.send(422, ‘Invalid username and password’);
});

We tell json-server to listen for HTTP POST requests on /sign-in. If the request contains a username field with a value of demo and password field with a value of demo, we return an object with the JWT token. If not, we send an HTTP 422 response to indicate that the username and password are invalid.
In addition, we also tell json-server to authorize all other requests:
// Protect other routes
server.use((req, res, next) => {
if (isAuthorized(req)) {
console.log(‘Access granted’);
next();
} else {
console.log(‘Access denied, invalid JWT’);
res.sendStatus(401);
}
});

// Check whether request is allowed
function isAuthorized(req) {
let bearer = req.get(‘Authorization’);
if (bearer === ‘Bearer ‘ + jwtToken) {
return true;
}
return false;
}

If the client’s HTTP request contains an Authorization header with the JWT token, we grant access. If not, we deny access and send an HTTP 401 response.
Finally, we tell json-server to load the API routes from db.json and start the server:
// API routes
server.use(router);

// Start server
server.listen(3000, () => {
console.log(‘JSON Server is running’);
});

To start our new back end, we run:
$ node json-server.js

For our convenience, let’s update the json-server script in package.json:
“json-server": "node json-server.js"

Now we can run:
$ npm run json-server

> todo-app@0.0.0 json-server /Users/jvandemo/Projects/sitepoint-editors/angular-todo-app
> node json-server.js

JSON Server is running

And voila, we have our own API server with authentication running.
Time to dig into the Angular side.
Adding Authentication Logic to our API Service
Now that we have an API endpoint to authenticate against, let’s add a new method to our ApiService to perform an authentication request:
@Injectable()
export class ApiService {

constructor(
private http: Http
) {
}

public signIn(username: string, password: string) {
return this.http
.post(API_URL + ‘/sign-in’, {
username,
password
})
.map(response => response.json())
.catch(this.handleError);
}

// …

}

When called, the signIn() method performs an HTTP POST request to our new /sign-in API endpoint, including the username and password in the request body.
If you’re not familiar with Angular’s built-in HTTP service, make sure to read Part 3 — Update the Todo service to communicate with a REST API.
Continue reading %Angular 2 Authentication: Protecting Private Content%

Link: https://www.sitepoint.com/angular-2-authentication-protecting-private-content/

Authentication with Angular and Auth0

This article was originally published on the Auth0.com blog, and is republished here with permission.
In this tutorial, we’re going to build an Angular application and add login functionality using token-based authentication with Auth0.
You can check out the completed code example from our GitHub repo.
The Angular Ecosystem
AngularJS 1.x was highly regarded as a robust framework for building single-page applications (SPAs). It did a lot of things well, fell short on some, but overall allowed developers to quickly build powerful applications.
While AngularJS (1.x) is a framework, Angular is an entire platform for building modern applications. Alongside the core Angular library, the platform ships with a powerful command line interface (CLI) called Angular CLI that allows developers to easily scaffold their applications as well as control the build system. Angular Platform Server brings server-side rendering to Angular applications. Angular Material is the official implementation of Google’s Material Design, which allows developers to build beautiful applications with ease.
Our App: Daily Deals

The app we’re building today is called Daily Deals. The Daily Deals app displays a list of deals and discounts on various products. We’ll have a list of publicly available deals that anyone can see and a list of private deals available only to registered members. The private deals are exclusive to registered members, and should hopefully be better.
Serving the Daily Deals
We’ll have to get our daily deals from somewhere. Let’s build a very simple Node.js back end to serve the deals. We’ll have a publicly accessible route serving public deals and a protected route that can only be called by authenticated users. For now, we’ll make both of the routes public and worry about the authentication piece later. Take a look at our implementation below:
‘use strict’;
// Load dependencies
const express = require(‘express’);
const app = express();
const cors = require(‘cors’);
const bodyParser = require(‘body-parser’);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

// Public route
app.get(‘/api/deals/public’, (req, res)=>{
let deals = [
// Array of public deals here
];
res.json(deals);
})

// Private route
app.get(‘/api/deals/private’, (req,res)=>{
let deals = [
// Array of Private Deals here
];
res.json(deals);
})

app.listen(3001);
console.log(‘Serving deals on localhost:3001’);

Both our server and the Angular app we are building will require Node.js and NPM, so be sure to have those installed before continuing. Check out the GitHub repo to get our list of daily deals or create your own. The model for each deal will be as follows:
{
id: 1234,
name: ‘Name of Product’,
description: ‘Description of Product’,
originalPrice: 19.99, // Original price of product
salePrice: 9.99 // Sale price of product
}

When you’re happy with the public and private deals, launch the server by running node server and navigate to both localhost:3001/api/deals/public and localhost:3001/api/deals/private to make sure you can see the list of deals you added. Next, let’s set up our Angular front end.
Angular Front End Setup
One of the best ways to start building a new Angular app is with the official Angular CLI. The CLI can take care of scaffolding the initial app, adding additional components, takes care of the build system and much more. In this tutorial, we’ll scaffold our initial app with the CLI.
If you don’t already have it installed, run:
npm install @angular/cli -g

This installs the Angular CLI globally. We’ll interact with the CLI using the ng command. To create a new application, choose a directory and run:
ng new ng2auth –routing –skip-tests

This will create a new Angular application with routing and no initial test files for the root component. The app will be created in its own folder in the current directory, and the CLI will download all of the required npm packages and basically set everything up for us.
Once ng new is finished, enter the new directory and run the ng serve command and the Webpack based build system will take care of compiling our app from TypeScript to JavaScript and will serve our app on localhost:4200. The ng serve command will also kick off a live sync process, so any time we make a change our app will automatically recompile.
Let’s head over the localhost:4200 for now to make sure that everything is working as expected so far. If you see a message saying “app works!”, you’re golden. Next, let’s examine how our Angular app is scaffolded.
The ng new command scaffolded our Angular app and added a lot of files. Many of these we can ignore for now like the e2e folder, which would contain our end-to-end tests. Open up the src directory. In the src directory, we can see some familiar files like index.html, styles.css, and so on. Open up the app directory.
The app directory contains the bulk of our application. By default, we’re presented with the following files:

app.component.css – Holds the CSS styles for our root component
app.component.html – Holds the HTML view for our root component
app.component.ts – Holds the TypeScript logic for our root component class
app.module.ts – Defines our global app dependencies
app-routing.module.ts – Defines our app’s routes.

Each Angular component we write will have at a minimum the *.component.ts file, the others are optional. Our application is going to have three components. The main or root component, a component to display the public deals, and a component to display private deals. For our root component, we’ll inline the template and styles. Let’s make the following edits and run the following CLI commands:

Delete app.component.css and app.component.html files. We’ll define all we need for our root component in the app.component.ts file.
Create a public-deals component by running ng g c public-deals –no-spec. This component will take care of getting and displaying the public deals data.
Create a private-deals component by running ng g c private-deals –no-spec. This component will take care of getting and displaying the private deals data.
Create a callback.component.ts file by running ng g c callback –it –is –flat –no-spec.
Create a deal file by running ng g class deal –no-spec. This file will hold our deal class, which will let Angular know the structure of a deal.
Create a deal.service.ts file by running ng g s deal –no-spec. Here we’ll add the functionality to get and retrieve the deal data from our API.

Note: g is a shortcut for generate, and c and s are shortcuts for component and service, respectively. Therefore, ng g c is equivalent to ng generate component. The –no-spec flag indicates that *.spec.ts files should not be generated. The –it and –is flags stand for “inline template” and “inline styles” and –flat indicates that a containing folder should not be created.
Adding HTTP Client Module
We’re going to be making HTTP requests to our API in our Angular app. To do so, we need to add the correct module to our app.module.ts file. Let’s do so now by importing the HttpClientModule and adding it to our @NgModule’s imports array like so:
// app.module.ts

import { HttpClientModule } from ‘@angular/common/http’;

@NgModule({
declarations: [

],
imports: [
…,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Adding Bootstrap CSS
We’re going to use Bootstrap to style our application, so let’s include the CSS in the of our index.html file like so:
<!– src/index.html –>

<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

Building the Root Component
Every Angular application must have a root component. We can name it whatever we want, but the important thing is that we have one. In our application, the app.component.ts file will be our root component. Let’s take a look at our implementation of this component.
// app.component.ts
import { Component } from ‘@angular/core’;

@Component({
selector: ‘app-root’,
template: `
<div class="container">
<nav class="navbar navbar-default">
<div class="navbar-header">
<a class="navbar-brand" routerLink="/dashboard">{{ title }}</a>
</div>
<ul class="nav navbar-nav">
<li>
<a routerLink="/deals" routerLinkActive="active">Deals</a>
</li>
<li>
<a routerLink="/special" routerLinkActive="active">Private Deals</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a>Log In</a>
</li>
<li>
<a>Log Out</a>
</li>
</ul>
</nav>
<div class="col-sm-12">
<router-outlet></router-outlet>
</div>
</div>
`,
styles: [
`.navbar-right { margin-right: 0px !important}`
]
})
export class AppComponent {
title = ‘Daily Deals’;

constructor() {}
}

We’ve created our root component. We added an inline template and some inline styles. We haven’t added all the functionality yet, so every user will be able to see all the links and the login and logout buttons. We’ll wait to implement those a little bit. We’re also displaying the <router-outlet> element. This is where our routed components will show.
Routing
Since we initialized our app with the –routing flag, the architecture for routing is already set up for us. Let’s update it so that our Deals component shows by default. We’ll also set up all the routes necessary for our app.
Open the app-routing.module.ts file and add the following:
// app-routing.module.ts
import { NgModule } from ‘@angular/core’;
import { Routes, RouterModule } from ‘@angular/router’;
import { CallbackComponent } from ‘./callback.component’;
import { PublicDealsComponent } from ‘./public-deals/public-deals.component’;
import { PrivateDealsComponent } from ‘./private-deals/private-deals.component’;

const routes: Routes = [
{
path: ”,
redirectTo: ‘deals’,
pathMatch: ‘full’
},
{
path: ‘deals’,
component: PublicDealsComponent
},
{
path: ‘special’,
component: PrivateDealsComponent
},
{
path: ‘callback’,
component: CallbackComponent
}
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

We can just navigate to localhost:4200 in the browser and see our app displayed. We won’t see much yet, just the top navbar and a message saying that the deals component works.
The Deal Type
TypeScript allows us to define the structure or type of our objects. This serves a bunch of useful purposes. For one, if we define the structure of an object, we’ll be able to get all of the object’s data via IntelliSense. We can additionally test our components easier by knowing the data structure or type of object we are dealing with.
For our app, we’ll create one such type. In the deal.ts file, we’ll define a type of Deal. Let’s see how we’ll accomplish this.
// deal.ts
export class Deal {
id: number;
name: string;
description: string;
originalPrice: number;
salePrice: number;
}

Now we can declare objects in our Angular application to be a type of deal. These objects will gain all of the properties and methods of the deal type. We’re only defining properties here; we won’t have any methods.
Continue reading %Authentication with Angular and Auth0%

Link: https://www.sitepoint.com/authentication-angular-auth0/

Building a Twitter Client with NodeJS and Angular

In this tutorial, we’re going to look at how to build a basic Twitter client with NodeJS, and an Angular application to display your home timeline of tweets. This is a rapid tour with things to consider while setting up your own Twitter client and Angular application.
First, we’re going to build a NodeJS server, which will handle communicating between the Twitter API and the Angular application. Then, we’ll build up the Angular application to display and interact with your Twitter timeline.
While you may be able to go through this tutorial without any prior NodeJS or Angular experience, I’ll assume some prior knowledge in the article.
Setting Up the Project
You’ll need a recent version of NodeJS set up on your machine. Then ensure you have the Angular CLI. The links provided give you a good place to start if you need help with either of those tasks.
The project source code can be found on GitHub. You can get it all running locally by either cloning it with Git or downloading the files from the repo’s GitHub archive.
git clone https://github.com/sitepoint-editors/twitter-angular-client

Once you have the files, from your terminal you’ll need to run npm install to get all of the dependencies installed. Then we can get to work!
Creating a Twitter Client in NodeJS
To access Twitter’s API, we need to register for a new “app”, which is essentially a way for Twitter to give us a set of credentials. These are unique for your application, so don’t share them publicly anywhere. You must, of course, have a Twitter account to access the data.
To start, go to https://apps.twitter.com/ and select Create New App. You can fill out the name, description, and website URL for your app. (You can use a fake URL for now. If you publish your app it should be your actual website.)
From there, you’ll see the new app page with your details. Go to the Keys and Access Tokens page, where you can see a button to Create my access token near the bottom. Click the button, and then you should see four values: Consumer Key (API Key), Consumer Secret (API Secret), Access Token, and Access Token Secret. We’ll use these in a moment, so be sure to keep this information handy.
Creating the Twitter Client in NodeJS
Now it’s time to dig into our NodeJS server, which will bridge the gap between Twitter’s API and the Angular app. In the project, you should see the server.js file, which you’ll need to open and tweak.
First, you’ll need to update the block that contains the credentials you received from the Twitter app earlier. You should copy those values into the block here. We’re using a Twitter package called Twit to help us connect to Twitter, though there are others available with various levels of functionality.
const client = new Twitter({
consumer_key: ‘CONSUMER_KEY’,
consumer_secret: ‘CONSUMER_SECRET’,
access_token: ‘ACCESS_TOKEN’,
access_token_secret: ‘ACCESS_TOKEN_SECRET’
});

Now we should be able to connect to Twitter. We’re also using the popular ExpressJS to create and manage our server. Now that you have the credentials installed, you can run the server.
node server

Our next step is to make several routes that will handle the HTTP requests our Angular application will need to make to load the Twitter data. Our first route is to get the current user, and validate their credentials. The Access Token and Secret you provided are linked to your Twitter account, so you’ll be the authorized user in this case. When this route is called, it will call the Twitter account/verify_credentials endpoint and return an object containing your user data.
app.get(‘/api/user’, (req, res) => {
client.get(‘account/verify_credentials’).then(user => {
res.send(user)
}).catch(error => {
res.send(error);
});
});

The next route we’ll create is to get your home timeline. It requests the statuses/home_timeline endpoint, and passes a few parameters to give us more of the data we need.
Due to rate limiting on the Twitter API, we’ve implemented a simple cache that will only request new data once a minute (which is the max rate before you receive errors). It basically keeps track of the last response and the time it was requested, only allowing new requests to Twitter to run after a minute. Rate limiting is a primary design consideration to have when building a Twitter app.
let cache = [];
let cacheAge = 0;

app.get(‘/api/home’, (req, res) => {
if (Date.now() – cacheAge > 60000) {
cacheAge = Date.now();
const params = { tweet_mode: ‘extended’, count: 200 };
if (req.query.since) {
params.since_id = req.query.since;
}
client
.get(`statuses/home_timeline`, params)
.then(timeline => {
cache = timeline;
res.send(timeline);
})
.catch(error => res.send(error));
} else {
res.send(cache);
}
});

Finally, we create a set of routes to handle like/unlike and retweet/unretweet actions for a tweet. This will allow us not only to read data, but also take action. These will require that you’ve set the application Access Level to Read and write (in case you changed it in the Twitter app settings).
app.post(‘/api/favorite/:id’, (req, res) => {
const path = (req.body.state) ? ‘create’ : ‘destroy’;
client
.post(`favorites/${path}`, {id: req.params.id})
.then(tweet => res.send(tweet))
.catch(error => res.send(error));
});

app.post(‘/api/retweet/:id’, (req, res) => {
const path = (req.body.state) ? ‘retweet’ : ‘unretweet’;
client
.post(`statuses/retweet/${req.params.id}`)
.then(tweet => res.send(tweet))
.catch(error => res.send(error));
});

There are many Twitter APIs for engaging with Twitter data, but the fundamental rules remain the same. The only major issue here is we’ve hard-coded credentials to a single user, which you’d need in order to set up your own OAuth server (or use an existing one) to handle the authentication aspects, which you can learn more about on Twitter Authentication documentation.
Creating the Angular App
Now it’s time to turn our attention to the Angular application that uses the server we created. We’ll take a look at the key aspects of the application and how they work to create the final result. We’ve built this application using Clarity for the UI layer (it gives us many useful layout components), but otherwise everything is just Angular.
To run the Angular application, just run the following command and then open up http://localhost:4200:
ng serve

Inside of the application, we have a model at src/app/tweet.ts which contains the TypeScript interface that describes most of the properties of a tweet (some have been omitted). I believe it’s essential to describe your types properly for large-scale Angular applications as well as smaller ones, so this interface gives us the shape of a tweet.
Angular TwitterService
First, we’ll need a service that can make requests to our NodeJS server to get the latest tweets. In Angular, the HttpClient is the utility you use to make HTTP requests, so I’ve created an Angular service to encapsulate the logic for these calls. Open up src/app/twitter.service.ts and you’ll see the following code:
import { Injectable } from ‘@angular/core’;
import { HttpClient } from ‘@angular/common/http’;
import { environment } from ‘../environments/environment’;
import { Tweet } from ‘./tweet’;

export interface TwitterResponse {
data: any;
resp: any;
}

@Injectable()
export class TwitterService {

constructor(private http: HttpClient) { }

user() {
return this.http.get(`${environment.api}/user`);
}

home(since?: string) {
return this.http.get<TwitterResponse>(`${environment.api}/home?since=${since}`);
}

action(property: ‘favorite’|’retweet’, id: string, state: boolean) {
return this.http.post<TwitterResponse>(`${environment.api}/${property}/${id}`, {state});
}
}

This is a fairly basic service, which has methods to build a request for each API that we’ll support. The user method will return the current user (which will always be you). The home method will return the latest 200 tweets in your home timeline (or how ever many appeared since the last tweet specified). Finally, the action property handles making either a favorite or retweet call, by sending a boolean state value to toggle the status.
This service is generic, and each of these methods returns an Observable. If you want to learn more about them, you can read about Functional Reactive with RXJS, but the way they’re used here is similar to how a promise works. We’ll see how to use them in a moment.
Using the Angular TwitterService to load user
We’ll use the TwitterService in a few places, starting with loading the AppComponent. We’ll use it to load the user details (which appears in the top corner), and to load the list of tweets for the home page. Open up src/app/app.component.ts and you should see the following code:
import { Component , OnInit } from ‘@angular/core’;
import { TwitterService } from ‘./twitter.service’;
import { Tweet } from ‘./tweet’;

@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.scss’],
providers: [TwitterService]
})
export class AppComponent implements OnInit {
user;

constructor(private twitter: TwitterService) {}

ngOnInit() {
this.twitter.user().subscribe(user => this.user = user.data);
}
}

The AppComponent does one main thing using our TwitterService. The ngOnInit method fires as soon as the component has initialized, and requests the user data. Here we’re using the Observable returned by the TwitterService.user method, and when we use subscribe it will trigger the actual HTTP request to fire. Once it’s returned, the callback function stores the user property, which is used to display content in the navbar. You can see the user property bindings in the component template below, such as user.profile_image_url_https:
<clr-main-container>
<clr-header class=”header-4">
<div class="branding">
<a class="nav-link">
<div class="title">Twangular</div>
</a>
</div>
<div class="header-actions" *ngIf="user">
<a class="nav-link">
<span class="nav-text">
<img [src]="user.profile_image_url_https" class="avatar" />
@
</span>
</a>
</div>
</clr-header>
<div class="content-container">
<main class="content-area">
<app-tweets></app-tweets>
</main>
</div>
</clr-main-container>

Also, the use of <app-tweets></app-tweets> will insert the TweetsComponent, which handles the actual loading and display of tweets, so let’s take a look at it now.
Continue reading %Building a Twitter Client with NodeJS and Angular%

Link: https://www.sitepoint.com/building-twitter-app-using-angularjs/