Accessing parent Route params in Angular

With the router/URL being an application’s “source of truth”, we need to be able to access parts of the URL for data purposes, such as grabbing a dynamic :id property from the URL, passing it into a service and bringing back the relevant data. Let’s look at how we can use Angular’s Observable-driven Router so get automatic updates when a parent route changes.

Table of contents

Scenario
Parent Route Param subscriptions

Scenario
I’m currently working on building out Ultimate Angular’s platform, and as such have these routes (in the URL, not my routing definitions) – with us assuming 1234 is our dynamic :id:
/admin/courses/1234/metadata
/admin/courses/1234/curriculum
/admin/courses/1234/prices
/admin/courses/1234/coupons

What this structure allows me to do is click a particular “course” from /admin/courses, and be navigated to the /1234/metadata view where I can edit the course’s name, author and so forth.
Parent Route Param subscriptions
What I needed to do is (based on the parent’s param), is go off to my Store and fetch the appropriate course I’m viewing.
First let’s walk through the routes:
// routes
export const ROUTES: Routes = [
{
path: ”,
canActivate: [CoursesGuard],
component: CoursesComponent,
},
{
path: ‘:id’,
canActivate: [CoursesGuard],
component: CourseComponent,
children: [
{ path: ”, redirectTo: ‘metadata’, pathMatch: ‘full’ },
{ path: ‘metadata’, component: CourseMetadataComponent },
{ path: ‘curriculum’, component: CourseCurriculumComponent },
{ path: ‘prices’, component: CoursePricesComponent },
{ path: ‘coupons’, component: CourseCouponsComponent },
],
},
];

When my path is ”, I use the CoursesComponent, and when we navigate to (for example /courses/1234/) – the CourseComponent is loaded (non-plural version). At this point, this CourseComponent is simply a container which renders a . Once we hit that :id, we’re directed to the first child route, metadata.
Let’s look what’s inside the CourseMetadataComponent, paying attention to ActivatedRoute and the course$ Observable:
// … other imports etc.
import { ActivatedRoute } from ‘@angular/router’;

@Component({
selector: ‘course-metadata’,
styleUrls: [‘course-metadata.component.scss’],
template: `
<div class=”course-metadata">
{{ course$ | async | json }}
</div>
`,
})
export class CourseMetadataComponent {
course$ = this.router.parent.params.switchMap(params => {
return this.store
.select(getCoursesState)
.map((courses: any) => courses.courses.find(course => course._id === params.id));
});

constructor(
private router: ActivatedRoute,
private store: Store<CoursesState>
) {}

}

At this point, the switchMap is given the params Object, which as you can see is driven from this.router.parent.params – which you may have used this before (without the .parent):
// not the parent, it’s the current param
course$ = this.router.params.switchMap(params => {
// do something with local "params"
});

So what is params when we do this?
course$ = this.router.parent.params.switchMap(params => {
// params = { id: 1234 }
});

In my case, with /admin/courses/1234/metadata, the params on the parent are in fact an Object containing { id: 1234 }.
This means from */1234/metadata, */1234/curriculum, */1234/prices and */1234/coupons – I have access to 1234 for passing off into ngrx/store to fetch the correct course. The courses are always available when hitting these routes because I’m using:
{ canActivate: [CoursesGuard] }

This way, it’ll make an API request if ngrx/store doesn’t contain any courses, otherwise it’ll pass the API request and head straight across to the correct course, pulling the data from the pre-populated store.

Link: https://toddmotto.com/angular-parent-routing-params

New HTTP Interface With Interceptors

In this blog post, I want to explore the latest HTTP interface from Angular which was introduced in Angular 4.3.
We all need to get our data from a source, mostly this is done via HTTP and any REST backend (like Node or ASP.NET Core, etc.) or even from files in the *.json format. However, this has been possible for a while and is one of the key features of an SPA, but Angular introduced an improved version of the HTTP API in version 4.3. Let’s take a look at this one.

Link: https://dzone.com/articles/new-http-interface-with-interceptors?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Angular Form Validations With Redux for Multiple Routes

Many front-end applications require the extensive use of forms to allow users to enter information. Angular supports various mechanisms to handle forms, but I’ve struggled to figure out how to handle validations of data on different pages/routes. Below is a pattern I’ve used based on Redux which doesn’t leverage much of the Angular forms functionality but works very nicely for me.
Initially, I thought that my requirements would be pretty straight forward and common for single-page applications. However, there were two things which I didn’t manage to address with core Angular forms functionality.

Link: https://dzone.com/articles/angular-form-validations-with-redux-for-multiple-r?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Angular Authentication With OpenID Connect and Okta in 20 Minutes

Angular (formerly called Angular 2.0) is quickly becoming one of the most powerful ways to build a modern single-page app. A core strength is Angular’s focus on building reusable components, which help you decouple the various concerns in your application. Take authentication, for example. It can be painful to build, but once you wrap it in a component, the authentication logic can be reused throughout your application.
The Angular CLI makes it easy to scaffold new components and even entire projects. If you haven’t used the Angular CLI to quickly generate Angular code, you’re in for a treat!

Link: https://dzone.com/articles/angular-authentication-with-openid-connect-and-okt?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

MEAN Stack: Developing an app with Angular 2+ and the Angular CLI

The MEAN stack comprises of advanced technologies used to develop both the server-side and the client-side of a web application in a JavaScript environment. The components of the MEAN stack include the MongoDB database, Express.js (a web framework), Angular (a front-end framework), and the Node.js runtime environment. Taking control of the MEAN stack and familiarizing different JavaScript technologies during the process will help you in becoming a full-stack JavaScript developer.
JavaScript’s sphere of influence has dramatically grown over the years and with that growth, there is an ongoing desire to keep up with the latest trends in programming. New technologies have emerged and existing technologies have been rewritten from the ground up (I am looking at you, Angular).
This tutorial intends to create the MEAN application from scratch and serve as an update to the original MEAN stack tutorial. If you are familiar with MEAN and want to get started with the coding, you can skip to the overview section.
Introduction to MEAN Stack
Node.js – Node.js is a server-side runtime environment built on top of Chrome’s V8 JavaScript engine. Node.js is based on an event-driven architecture that runs on a single thread and a non-blocking IO. These design choices allow you to build real-time web applications in JavaScript that scale well.
Express.js – Express is a minimalistic yet robust web application framework for Node.js. Express.js uses middleware functions to handle HTTP requests and then either return a response or pass on the parameters to another middleware. Application-level, Router-level, and Error-handling middlewares are available in Express.js.
MongoDB – MongoDB is a document-oriented database program where the documents are stored in a flexible JSON-like format. Being an NOSQL database program, MongoDB relieves you from the tabular jargon of the relational database.
Angular – Angular is an application framework developed by Google for building interactive Single Page Applications. Angular, originally AngularJS, was rewritten from scratch to shift to a Component based architecture from the age old MVC framework. Angular recommends the use of TypeScript which, in my opinion, is a good idea because it enhances the development work-flow.
Now that we are acquainted with the pieces of the MEAN puzzle, let’s see how we can fit them together, shall we?
Overview
Here is a high-level overview of our application.

We will be building an Awesome Bucket List Application from the ground up without using any boilerplate template. The front-end will include a form that accepts your bucket list items and a view that updates and renders the whole bucket list in real-time.
Any update to the view will be interpreted as an event and this will initiate an HTTP request. The server will process the request, update/fetch the MongoDB if necessary, and then return a JSON object. The front-end will use this to update our view. By the end of this tutorial, you should have a bucket list application that looks like this.

The entire code for the Bucket List application is available on GitHub.
Prerequisites
First things first, you need to have Node.js and MongoDB installed to get started. If you are entirely new to Node, I would recommend reading the Beginner’s Guide to Node to get things rolling. Likewise, setting up MongoDB is easy and you can check out their documentation for installation instructions specific to your platform.
$ node -v
# v8.0.0

Start the mongo daemon service using the command.
sudo service mongod start

To install the latest version of Angular, I would recommend using Angular-CLI. It offers everything you need to build and deploy your angular application. If you are not familiar with the Angular CLI yet, make sure you check out The Ultimate Angular CLI Reference.
npm install -g @angular/cli

Create a new directory for our bucket list project. That’s where all your code will go, both the front end and the back end.
mkdir awesome-bucketlist
cd awesome-bucketlist

Creating the Backend Using Express.js and MongoDB
Express doesn’t impose any structural constraints on your web application. You can place the entire application code in a single file and get it to work, theoretically. However, your code base would be a complete mess. Instead, we are going to do this the MVC (Model, View, and Controller) way (minus the view part).
MVC is an architectural pattern that separates your models (the back-end) and views (the UI) from the controller (everything in between), hence MVC. Since Angular will take care of the front-end for us, we will have three directories, one for models and another one for controllers, and a public directory where we will place the compiled angular code.
In addition to this, we will create an app.js file that will serve as the entry point for running the Express server.

Although using a model and controller architecture to build something trivial like our bucket list application might seem essentially unnecessary, this will be helpful in building apps that are easier to maintain and refactor.
Initializing npm
We’re missing a package.json file for our back end. Type in npm init and, after you’ve answered the questions, you should have a package.json made for you.
We will declare our dependencies inside the package.json file. For this project we will need the following modules.

express: Express module for the web server
mongoose: A popular library for MongoDB
bodyparser: Parses the body of the incoming requests and makes it available under req.body
cors: CORS middleware enables cross-origin access control to our web server.

I’ve also added a start script so that we can start our server using npm start.
{
“name": "awesome-bucketlist",
"version": "1.0.0",
"description": "A simple bucketlist app using MEAN stack",
"main": "app.js",
"scripts": {
"start": "node app"
},

//The ~ is used to match the most recent minor version (without any breaking changes)

"dependencies": {
"express": "~4.15.3",
"mongoose": "~4.11.0",
"cors": "~2.8.3",
"body-parser": "~1.17.2"
},

"author": "",
"license": "ISC"
}

Now run npm install and that should take care of installing the dependencies.
Filling in app.js
First, we require all of the dependencies that we installed in the previous step.
// We will declare all our dependencies here
const express = require(‘express’);
const path = require(‘path’);
const bodyParser = require(‘body-parser’);
const cors = require(‘cors’);
const mongoose = require(‘mongoose’);

//Initialize our app variable
const app = express();

//Declaring Port
const port = 3000;

As you can see, we’ve also initialized the app variable and declared the port number. The app object gets instantiated on the creation of the Express web server. We can now load middleware into our Express server by specifying them with app.use().
//Middleware for CORS
app.use(cors());

//Middleware for bodyparsing using both json and urlencoding
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

/*express.static is a built in middleware function to serve static files.
We are telling express server public folder is the place to look for the static files
*/
app.use(express.static(path.join(__dirname, ‘public’)));

The app object can understand routes too.
app.get(‘/’, (req,res) => {
res.send("Invalid page");
})

Here, the get method invoked on the app corresponds to the GET HTTP method. It takes two parameters, the first being the path or route for which the middleware function should be applied.
The second is the actual middleware itself and it typically takes three arguments: The req argument corresponds to the HTTP Request; the res argument corresponds to the HTTP Response; and next is an optional callback argument that should be invoked if there are other subsequent middlewares that follow this one. We haven’t used next here since the res.send() ends the request-response cycle.
Add this line towards the end to make our app listen to the port that we had declared earlier.
//Listen to port 3000
app.listen(port, () => {
console.log(`Starting the server at port ${port}`);
});

npm start should get our basic server up and running.
By default, npm doesn’t monitor your files/directories for any changes and you have to manually restart the server every time you’ve updated your code. I recommend using nodemon to monitor your files and automatically restart the server when any changes are detected. If you don’t explicitly state which script to run, nodemon will run the file associated with the main property in your package.json.
npm install -g nodemon
nodemon

We are nearly done with our app.js file. What’s left to do? We need to

Connect our server to the database.
Create a controller which we can then import to our app.js.

Setting up mongoose
Setting up and connecting a database is straightforward with MongoDB. First, create a config directory and a file named database.js to store our configuration data. Export the database URI using module.exports.
// 27017 is the default port number.
module.exports = {
database: ‘mongodb://localhost:27017/bucketlist’
}

And establish a connection with the database in app.js using mongoose.connect().
// Connect mongoose to our database
const config = require(‘./config/database’);
mongoose.connect(config.database);

"But what about creating the bucket list database?", you may ask. The database will be created automatically when you insert a document into a new collection on that database.
Working on the controller and the model
Now let’s move on to create our bucket list controller. Create a bucketlist.jsfile inside the controller directory. We also need to route all the /bucketlist requests to our bucketlist controller (in app.js).
const bucketlist = require(‘./controllers/bucketlist’);

//Routing all HTTP requests to /bucketlist to bucketlist controller
app.use(‘/bucketlist’,bucketlist);

Here is the final version of our app.js file.
Continue reading %MEAN Stack: Developing an app with Angular 2+ and the Angular CLI%

Link: https://www.sitepoint.com/mean-stack-angular-2-angular-cli/

Learn MVC Using Angular Dynamic Localization

Introduction
This article demonstrates low to use Agular dynamic localization in MVC using the Angular i18n package in Visual Studio 2017.
Localization
Localization is a very important part of region based applications. It customizes your application for a given culture and locale. So, this localization can change dynamically using Angular Dynamic Locale Module.

Link: https://dzone.com/articles/learn-mvc-using-angular-dynamic-localization?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

The Ultimate Guide to Progressive Web Applications

Progressive Web Apps, aka PWAs, are the best way for developers to make their web apps load faster and perform better. In a nutshell, PWAs are websites that use recent web standards to allow for installation on a user’s computer or device and deliver an app-like experience to those users.
Twitter recently launched mobile.twitter.com as a PWA built with React and Node.js. They’ve had a good experience with PWAs, showing that the technology is finally ready for the masses.

Link: https://dzone.com/articles/the-ultimate-guide-to-progressive-web-applications?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Learn MVC Using Angular and Web API and Deploy to IIS

Introduction:
In this article, we are going to:

Publish MVC using Angular.
Publish a Web API application.
Deploy these applications to the Internet Information Server v.10.

Publish MVC Using Angular
Open any MVC project using an Angular application in Visual Studio 2017. Here, I am going to deploy my previous application that I used in my previous article, “Learn MVC Using Angular Dynamic Control in DataTable.” The reason for this is that in this application, I have used a Web API and a SQL Server. So let us start.

Link: https://dzone.com/articles/learn-mvc-using-angular-and-web-api-and-deploy-to?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev