Welcome!

Machine Learning Authors: Kevin Jackson, Madhavan Krishnan, VP, Cloud Solutions, Virtusa, Pat Romanski, Elizabeth White, William Schmarzo

Related Topics: @CloudExpo, Java IoT, Machine Learning

@CloudExpo: Blog Feed Post

Angular 2: Guarding Routes | @CloudExpo #API #Cloud #Angular2

Here are some scenarios that require a certain validation to be performed

In this blog I’ll show you how to guard routes in Angular 2 Router (currently at 3.0.0-beta.2).

Let’s consider some scenarios that require a certain validation to be performed to decide if the user (or a program) is allowed to navigate to or leave the route:

  • Allowed to open the route only if the user is authenticated and authorized to do so.
  • Implement a multi-part form that consists of several components, and the user is allowed to navigate to the next form section only if the data entered in the current one is valid.
  • Allow to navigate to a route only after a certain data structures have been populated.
  • Remind the user about the unsaved changes if he or she tries to navigate from the route.

The router has the hooks that give you more control over the navigation to/from a route, and you can use these hooks to implement the any of above scenarios to guard the routes.

Angular includes a number of component lifecycle hooks that allow you to handle important events in the life of a component. First, it worth noting that the route configuration is done outside of the components. You configure routes in an object of type RouterConfig, then give it to the provideRouter() function, which in turn is given to the function bootstrap() that loads your app.

The type RouterConfig that implements the Route interface shown below:

export interface Route {
path?: string;
terminal?: boolean;
component?: Type | string;
outlet?: string;
canActivate?: any[];
canDeactivate?: any[];
redirectTo?: string;
children?: Route[];
}

While configuring routes you’ll typically use two properties from this interface: path and component. For example, an app that has two links Home and Product Details can specify and bootstrap the routes as follows:

bootstrap(RootComponent, [
provideRouter([
{path: '', component: HomeComponent},
{path: 'product', component: ProductDetailComponent}]),
{provide: LocationStrategy, useClass: HashLocationStrategy}
]);

But in this blog I’d like to you to get familiar with the properties canActivate and canDeactivate that allow you to hook up the routes with the guards. Basically you need to write a function(s) implementing the validating logic that will return either true or false and assign it to one of these properties. If canActivate is equal to true, the user can navigate to the route. If canDeactivate is true, the user can navigate from the route. Since each of these properties accept an array as a value, you can assign multiple functions (the guards) if you need to check more than one condition to allow or forbid the navigation.

Let’s create a simple app with Home and Product Details links to illustrate how you can protect the product route from the users who are not logged in. To keep the example simple, we won’t use an actual login service, but will generate the login status randomly.

We’ll create a guard class that implements the interface CanActivate, which declares only one function to implement: canActivate(). This function should contain the application logic that returns true or false. If the function returns false (the user is not logged in) the application will not navigate to the route and will print the error message on the console.

import {CanActivate} from "@angular/router";
import {Injectable} from "@angular/core";

@Injectable()
export class LoginGuard implements CanActivate{

canActivate() {
return this.checkIfLoggedIn();
}

private checkIfLoggedIn(): boolean{

// A call to the actual login service would go here
// For now we'll just randomly return true or false

let loggedIn:boolean = Math.random() < 0.5;

if(!loggedIn){
console.log("LoginGuard: The user is not logged in and can't navigate product details");
}

return loggedIn;
}
}

As you see from the code, our implementation of the function canActivate() will randomly return true or false emulating the user’s logged in status.

The next step is to update the router configuration so it uses our guard. The code snippet below shows how the function provideRouter() can look like for the app that has Home and Product Detail routes and the latter is protected by our LoginGuard:

provideRouter([
{path: '', component: HomeComponent},
{path: 'product', component: ProductDetailComponent,
canActivate:[LoginGuard]}
])

Adding one or more guards to the array given to the canActivate property will automatically invoke all guards one after the other. If any of the guards returns false, the navigation to the route will be prohibited.

But who will instantiate the class LoginGuard? Angular will do it for use using its dependency injection mechanism, but you have to mention this class in the list of providers which are needed for injection to work. We’ll just add the name LoginGuard to the list of providers in the bootstrap() function of our app:

bootstrap(RootComponent, [
provideRouter([
{path: '', component: HomeComponent},
{path: 'product', component: ProductDetailComponent,

canActivate:[LoginGuard]}]),
LoginGuard,
{provide: LocationStrategy, useClass: HashLocationStrategy}
]);

The complete code of the main app script is shown next:

import {bootstrap} from '@angular/platform-browser-dynamic';
import {Component} from '@angular/core';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';
import {provideRouter, ROUTER_DIRECTIVES} from '@angular/router';

import {HomeComponent} from './components/home';
import {ProductDetailComponent} from './components/product';

import {LoginGuard} from './guards/login.guard';

@Component({
selector: 'basic-routing',
directives: [ROUTER_DIRECTIVES],
template: `
<a>Home</a>
<a>Product Details</a>


` })
class RootComponent {}

bootstrap(RootComponent, [
provideRouter([
{path: '', component: HomeComponent},
{path: 'product', component: ProductDetailComponent,
canActivate:[LoginGuard]}]),
LoginGuard,
{provide: LocationStrategy, useClass: HashLocationStrategy}
]);

If you run this app and will try to lick on the Product Details link, it’ll either navigate to this route or print the error message on the browser console depending on the randomly generated value in the LoginGuard. The snapshot below was taken after the user tried to click on the Product Details link, but the LoginGuard “decided” that the user is not logged in.

ch3_loginguard

But if our unpredictable LoginGuard “decided” that the user is logged in, the screen will look as follows after clicking on the Product Details link:

nonguarded

In the above example we implemented the method canActivate() without providing any arguments to it. But this method can be used with the following signature:

canActivate(destination: ActivatedRouteSnapshot,
state: RouterStateSnapshot)

The values of the ActivatedRouteSnapshot and RouterStateSnapshot will be injected by Angular automatically, and may be quite handy if you want to analyze the current state of the router. For example, if you’d like to know the name of the route the user tried to navigate to, this is how to do it:

canActivate(destination: ActivatedRouteSnapshot,
state: RouterStateSnapshot) {

console.log(destination.component.name);
...
}

Implementing the CanDeactivate interface that would control the process of navigating from a route works similarly. Just create a guard class that implements the method canDeactivate(), for example:

class UnsavedChangesGuard implements CanDeactivate{

canDeactivate(){

alert("You have unsaved changes");
}
}

For a fancier way of displaying alerts use the MdDialog component from the Material Design 2 library (see https://github.com/angular/material2). This component will be released in the upcoming Alpha 7.

In this blog I didn’t show you the code of HomeComponent and ProductDetail component, but you can find them in the Github repo with the code samples from Chapter 3 in our book Angular 2 Development with TypeScript.

If you’re interested in learning Angular 2 in depth, enroll into one of our workshops. The next one we’ll run online starting from September 11, 2016.

Read the original blog entry...

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

@CloudExpo Stories
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
Enterprises are moving to the cloud faster than most of us in security expected. CIOs are going from 0 to 100 in cloud adoption and leaving security teams in the dust. Once cloud is part of an enterprise stack, it’s unclear who has responsibility for the protection of applications, services, and data. When cloud breaches occur, whether active compromise or a publicly accessible database, the blame must fall on both service providers and users. In his session at 21st Cloud Expo, Ben Johnson, C...
"We're developing a software that is based on the cloud environment and we are providing those services to corporations and the general public," explained Seungmin Kim, CEO/CTO of SM Systems Inc., in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Enterprises are adopting Kubernetes to accelerate the development and the delivery of cloud-native applications. However, sharing a Kubernetes cluster between members of the same team can be challenging. And, sharing clusters across multiple teams is even harder. Kubernetes offers several constructs to help implement segmentation and isolation. However, these primitives can be complex to understand and apply. As a result, it’s becoming common for enterprises to end up with several clusters. Thi...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
Data scientists must access high-performance computing resources across a wide-area network. To achieve cloud-based HPC visualization, researchers must transfer datasets and visualization results efficiently. HPC clusters now compute GPU-accelerated visualization in the cloud cluster. To efficiently display results remotely, a high-performance, low-latency protocol transfers the display from the cluster to a remote desktop. Further, tools to easily mount remote datasets and efficiently transfer...
"Codigm is based on the cloud and we are here to explore marketing opportunities in America. Our mission is to make an ecosystem of the SW environment that anyone can understand, learn, teach, and develop the SW on the cloud," explained Sung Tae Ryu, CEO of Codigm, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
In his session at 21st Cloud Expo, James Henry, Co-CEO/CTO of Calgary Scientific Inc., introduced you to the challenges, solutions and benefits of training AI systems to solve visual problems with an emphasis on improving AIs with continuous training in the field. He explored applications in several industries and discussed technologies that allow the deployment of advanced visualization solutions to the cloud.
"Infoblox does DNS, DHCP and IP address management for not only enterprise networks but cloud networks as well. Customers are looking for a single platform that can extend not only in their private enterprise environment but private cloud, public cloud, tracking all the IP space and everything that is going on in that environment," explained Steve Salo, Principal Systems Engineer at Infoblox, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventio...
"We're focused on how to get some of the attributes that you would expect from an Amazon, Azure, Google, and doing that on-prem. We believe today that you can actually get those types of things done with certain architectures available in the market today," explained Steve Conner, VP of Sales at Cloudistics, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"NetApp is known as a data management leader but we do a lot more than just data management on-prem with the data centers of our customers. We're also big in the hybrid cloud," explained Wes Talbert, Principal Architect at NetApp, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, provided a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to oper...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...