The Wayback Machine - https://web.archive.org/web/20160321024351/http://java.sys-con.com/node/3686948

Welcome!

Java IoT Authors: Victoria Livschitz, Pat Romanski, Elizabeth White, SmartBear Blog, Liz McMillan

Related Topics: @ThingsExpo, Java IoT, Mobile IoT, Microservices Expo, Linux Containers, Containers Expo Blog, IoT User Interface, Agile Computing, Video, Wearables, @CloudExpo, OpenStack Journal, @DevOpsSummit

@ThingsExpo: Blog Feed Post

Angular 2 Overview By @YFain | @ThingsExpo #DevOps #IoT #Microservices

The Angular 2 framework is a re-write of popular framework AngularJS

This article was excerpted from the book “Angular Development With TypeScript” (see http://bit.ly/1QYeqL0).

The Angular 2 framework is a re-write of popular framework AngularJS. In short, the newer version has the following advantages over AngularJS.

  • The code is simpler to write and read
  • It performs better  than AngularJS
  • It’s easier to learn
  • The application architecture is simplified as it’s component-based

This article contains a high-level overview of Angular highlighting improvements comparing to AngularJS. For a more detailed architecture overview of Angular visit product documentation at http://bit.ly/1TQJmwG.

Code Simplification
First of all, an Angular application consists of standard ES6 modules. Typically one module is one file. There is no need to use a framework-specific syntax for loading and using modules. Just use the universal module loader SystemJS (covered in Chapter 2) and add import statements to use functionality implemented in the loaded modules. You don’t need to worry about the proper order of the <script> tags in your HTML files. If a module A needs the functionality from a module B, just import the module B inside module A.

The HTML file of the landing page of your application just includes the framework modules, and your application code is bootstrapped by simple loading of the root component of your application. All child modules will be loaded automatically based on the import statements. Below is a typical content of the index.html of an Angular application. In the top portion you include the required framework modules, and at the bottom you configure the system loader and load the root component located in the file app/my_application.ts. The <app> tag is a selector defined in that root component.

<!DOCTYPE html>
<html>
<head>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/typescript/lib/typescript.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>

</head>
<body>
<app>Loading...</app>

<script>
System.config({
transpiler: 'typescript',
typescriptOptions: {emitDecoratorMetadata: true},
packages: {app: {defaultExtension: 'ts'}}
});
System.import('app/my_application');
</script>
</body>
</html>

The HTML fragment of each application component is either inlined inside of the component (the template property) or in the file referenced from the component using the property templateURL. The latter option allows designers to work on the UI of your application without the need to learn Angular.

An Angular component is a centerpiece of the new architecture. The next Figure shows a high-level diagram of a sample Angular application.

ch1_angular2_workflow

The simplest way of declaring a component is writing a class in TypeScript (you can use ES5, ES6, or Dart as well). Let’s do an experiment. We’ll give you a super brief intro on how to write Angular components in TypeScript followed by the sample code. See if you can understand the code with minimum explanations.

An annotated TypeScript class represents a component. The annotation @Component contains the property template that declares an HTML fragment to be rendered by the browser. The HTML piece may include the data binding expressions, which can be represented by double curly braces. If a view depends on other components, the @Component annotation has to list them in the property directives. The references to the event handlers are placed in the markup from the @Component section and are implemented as methods of the class.

The annotation @Component also contains a selector declaring the name of the custom tag to be used in HTML document. When Angular sees an HTML element with the name matching a selector, it knows which component implements it. The HTML fragment below illustrates a parent component with one child component :

<body>
<auction-application>
<search-product [productID]= "123"></search-product>
</auction-application>
</body>

A parent component sends the data to its child components using property binding (note the square brackets above), and children communicate with their parents by sending events. Figure 1.7 shows the main page (the parent component) with its child components surrounded with thick borders.

Below is a code sample of a SearchComponent, and we can include it in an HTML document as because its declaration includes the selector property with the same name.

@Component({
selector: 'search-product',
template:

` <form>
<div>
<input id="prodToFind" #prod>
<button (click)="findProduct(prod.value)">Find Product</button>
Product name: {{product.name}}</div>
</form>


` })
class SearchComponent {
@Input() productID: number;

product: Product; // code of the Product class is omitted

findProduct(prodName: string){
// Implementation of the click handler goes here
}
// Other code can go here
}

If you are familiar with any object-oriented language that has classes you should understand most of the above code. The annotated class SearchComponent declares a variable product, which may represent an object with multiple properties, one of which (name) is bound to the view ({{product.name}}). The #prod will have a reference to the hosting <input type=”text” /> element so you don’t need to query DOM to get the entered value.

The (click) notation represents a click event, and the event handler function gets the argument value from the input parameter productID that will be populated by the parent component via binding.

This was just a quick look at the sample component, but we’ll be providing a detailed description of what components are made up of starting from the next chapter.

If you never worked with classes before, no worries. We’ll cover them in Appendices A and B. The next Figure illustrates the inner working of a component.

ch1_angular_component

A component uses the data from a model (the M in the MVC pattern), which can be also represented by a class. In TypeScript the model class for a SearchComponent could look like this:

class Product{
id: number,
name: string;
description: string;
bid: number;
price: number;

// constructor and other methods go here
}

Note that TypeScript allows you to declare class variables with types. To let the UI component SearchComponent know about its model you can refer to it by declaring a class variable, e.g., product:

@Component { // code omitted for brevity}
class SearchComponent {
product: Product; // the model

findProduct(productID){
// The implementation of the click handler
// for the Find Components button goes here
}
}

If the search component may return multiple products we can declare an array to store them:

products: Array<Product>;

The generics notation (explained in Appendix B) tells the TypeScript compiler that only the objects of the type Product are allowed to be stored in this array.

In Angular there are no separate controllers (the C in the MVC pattern). The component includes all required code. In our example, the SearchProduct class would contain the code performing the controller’s responsibilities in addition to being a UI component on the HTML view. For a cleaner separation of TypeScript and HTML, the content of the template section of the @Component annotation can be stored in a separate file by using templateURL instead of template, but it’s a matter of your preference.

Developers who know AngularJS can think of a component as a directive with a view, but writing directives without views is still allowed.

Now let’s see how the design of Angular is simpler than of AngularJS. In AngularJS all directives were loaded to the global memory, whereas in Angular you specify the required directives on the component level providing better encapsulation.

You don’t have to deal with the hierarchy of scope objects as in AngularJS. Angular is component based, and the properties are created on the this object, which becomes the component’s scope.

Dependency Injection is a design pattern that inverts the way of creating objects your code depends on. Instead of explicitly creating object instances (e.g. with new) the framework will create and inject them into your code. Angular comes with a dependency injection module. We’ll cover dependency injection in Chapter 4.

In AngularJS there were several ways of injecting dependencies, which could be confusing at times. In Angular you can inject dependencies into the component only via its constructor. The following TypeScript code fragment shows how to inject the ProductService component into the SearchComponent. You just need to specify a provider and declare the constructor argument with the type that matches provider’s type.

@Component({
selector: 'search-product',
viewProvider: [ProductService],
template:[
<div>
...
<div>]
})
class SearchComponent {
products: Array<Product> = [];

constructor(productService: ProductService) {
this.products = this.productService.getProducts();
}
}

To summarize, Angular is simpler than AngularJS because of the following:

  • Each building block of your app is a component with well encapsulated functionality of a view, controller, and auto-generated change detector.
  • Components can be programmed as annotated classes.
  • A developer doesn’t have to deal with scope hierarchies.
  • Dependent components are injected via the component’s constructor.
  • Two-way binding is turned off by default.
  • Change detection mechanism was re-written and works faster.

The concepts of Angular are easy to understand for Java, C#, and C++ programmers, which represent the majority of enterprise software developers. Like it or not, but a framework becomes popular when it gets adopted by enterprises. Today AngularJS is widely adopted by the enterprises, and AngularJS skills are in big demand. Since developing applications with Angular is easier than with AngularJS this trend should continue.

Performance Improvements
To compare performance of AngularJS and Angular 2 the creators of these frameworks developed a benchmarking tool called Benchpress (see http://bit.ly/1IvgnKZ), which showed some serious performance improvements in the area of rendering and memory use.

The rendering improvements are mainly the result of the internal redesign of the Angular framework. The UI rendering and the application API were separated into two layers, which allows to run the non-UI related code in a separate Web Worker thread. Beside the ability to run the code of these layers concurrently, Web browsers allocate different CPU cores to these threads when available. You can find a detailed description of the new rendering architecture in the document titled Angular 2 Rendering Architecture available at http://bit.ly/1CEXjIl.

Creating a separate layer for rendering has an additional important benefit: an ability to use different renderers for different devices. Every component includes the @Component annotation that contains an HTML template defining the look of the component. If you want to create a component to display stock prices in the Web browser its UI portion may look as follows:

@Component({
selector: 'stock-price',
renderer: 'DOMRenderer',
template: '
<div>The price of an IBM share is $165.50</div>
'
})
class StockPriceComponent {
...
}

Currently, DOMRenderer is the only renderer, so you don’t even need to include it in the @Component annotation. But the Angular team already works on creating native renderers for mobile devices running iOS and Android. Such renderers should be released in the near future, and Angular applications won’t need to run inside the Web View (embedded Web browser) on mobile devices – they’ll use native UI components.

A new and improved change detection mechanism is yet another contributor to better performance. Angular doesn’t use two-way binding unless you manually program it. One-way binding simplifies the detection of the changes in an application that may have lots of interdependent bindings. Now if a component has only internal immutable objects, you can mark it as such so it won’t be checked when a change is detected in another component.

Although Angular 2 is a complete re-design of Angular 1, those of you who use AngularJS can start writing code in Angular 2 style by using ng-forward (see http://bit.ly/1PNXFmH). The other approach is to start gradually switching to a newer version of this framework by running Angular 2 and Angular 1 in the same application (see http://bit.ly/1YixNzE), but this would increase the size of the application.

“To learn more about Angular see the book “Angular Development with TypeScript” at http://bit.ly/1QYeqL0 and save 39% with discount code faindz.  For the up to date information about our Angular 2 training visit this page.

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

@ThingsExpo Stories
SYS-CON Events announced today that Chetu Inc., a worldwide leader in custom software solutions for niche businesses, software-defined storage and data services platform, will exhibit at SYS-CON's @ThingsExpo, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled ni...
SYS-CON Events announced today BZ Media LLC has been named “Media Sponsor” of SYS-CON's 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. BZ Media LLC is a high-tech media company that produces technical conferences and expositions, and publishes a magazine, newsletters and websites in the software development, SharePoint, mobile development and Commercial Drone markets.
@ThingsExpo has been named the ‘Top WebRTC Influencer' by iTrend. iTrend processes millions of conversations, tweets, interactions, news articles, press releases, blog posts - and extract meaning form them and analyzes mobile and desktop software platforms used to communicate, various metadata (such as geo location), and automation tools. In overall placement, @ThingsExpo ranked as the number one ‘WebRTC Influencer' followed by @DevOpsSummit at 55th.
“Today’s generation of customers are always connected and well informed, but businesses are lagging behind in terms of both understanding and engaging their customers across all their channels in ways that are both relevant and consistent,” said Brian Walker, chief strategy officer, SAP Hybris. Only one in four companies are enabling omnichannel customer engagement, whereby they have a unified, “single view” of the customer and are delivering a consistent, contextual, and relevant experience a...
Zones, Inc., illustrated how technology solutions can improve patient care at the HIMSS16 Conference and Exhibition. Zones’ healthcare experts showcased technology to enhance patient care, ensure access to electronic medical and health records (EMR/EHR), design and implement mobility initiatives, and safeguard network and data security. Supporting every aspect of IT in the healthcare environment, Zones’ healthcare team can recommend the most productive and scalable IT solutions to ensure a high...
Symantec Corp. has announced the worldwide availability of Encryption Everywhere, a website security package available through web hosting providers. Encryption Everywhere lets web hosting providers integrate encryption into every website from the moment it is created. With the new web security service, hosting providers can offer a variety of flexible options, including basic website encryption included as part of any hosted service, and a number of premium security packages with increasingly s...
Electric Imp has expanded its focus to align with evolving commercial and industrial Internet of Things (IoT) opportunities. ”As our platform evolves, it is able to satisfy markets more demanding than the initial consumer segment,” said Hugo Fiennes, CEO and co-founder of Electric Imp. "Delivering over 500,000 units through our consumer device partners helped prove the scalability, reliability and usability of our platform, and now we are targeting our unique architecture at the problems facing...
SYS-CON Events announced today that LeaseWeb USA Inc., one of the world's largest hosting brands, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. LeaseWeb USA Inc. was established in 2011, a separate and distinct operating entity providing services in the USA. LeaseWeb is a trusted partner to mid-market companies, helping them find the right solution to their critical cloud-hosted needs from our global...
Exosite has announced its Taipei Office has formally been established. Exosite’s Taiwan operations have grown from the Taichung team, primarily focused on research and development, into a full-service IoT enablement organization with development and consulting capabilities. The new Taipei office is located in the Taipei Minsheng Dunhua district, surrounded by all its hardware and channel partners. Exosite will devote its time to the Taiwan market and expand its business into the Asia-Pacific mar...
*This is part of a series of blogs examining Sensor-2-Server (S2S) communications, development, security and implementation. For the past two weeks, we’ve taken an in-depth look at what Sensor-2-Server communications are, how to implement these systems, and some of the specific aspects of communication that these systems facilitate. This week, for our final installment, we’ll examine some of the benefits, as well as security considerations, for S2S communications.
As devices, sensors, objects and people are given digital identities that connect them to the Internet by the billions, the need for security and privacy becomes a critical factor for both market adoption and safety. The 40-year-old security methods we now use on our PCs and networks cannot address many of these IoT devices.
Internet of Things (IoT) platforms have evolved. Advances in technology make it possible for facilities to become more data-driven by connecting to energy assets, thereby improving building resiliency and reducing energy costs. By creating an Energy Network of Things, facilities can manage energy assets in real-time, institute system-wide operational oversight and compliance, execute energy efficiency programs, utilize real-time data, and support budgeting and asset planning across local and geo...
Two-thirds of organizations implementing hybrid cloud report they’re already gaining competitive advantage from their hybrid environments and are nearly three times as likely to use it to assemble data assets or monetize data, according to findings released by IBM (NYSE: IBM). With a hybrid cloud approach, organizations can be selective about when to use cloud and when to use traditional IT infrastructure – delivering the best functionality while meeting speed and flexibility needs, as well a...
SYS-CON Events announced today CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. CrowdReviews.com is the first buyer’s guide that ranks products and services based on client reviews.
For basic one-to-one voice or video calling solutions, WebRTC has proven to be a very powerful technology. Although WebRTC’s core functionality is to provide secure, real-time p2p media streaming, leveraging native platform features and server-side components brings up new communication capabilities for web and native mobile applications, allowing for advanced multi-user use cases such as video broadcasting, conferencing, and media recording.
SYS-CON Events announced today Object Management Group® has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY, and the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Pythian, a global IT services company specializing in helping companies adopt disruptive technologies to optimize revenue-generating systems, has been named "Bronze Sponsor" of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2015 at the Javits Center in New York, New York. Pythian, a 400-person global IT services company that helps companies compete by adopting disruptive technologies, announced today that CEO Paul Vallée has been named “Diversi...
transform operational efficiency and safety for businesses and communities, especially during critical situations. During these critical events, man-made incidents or natural disasters, identifying and reaching employees with reliable and automated communications can not only protect business assets, but can be the difference between life and death. In his session at @ThingsExpo, Imad Mouline, chief technology officer for Everbridge, will highlight incident communications best practices and ...
Big Data, cloud, analytics, contextual information, wearable tech, sensors, mobility, and WebRTC: together, these advances have created a perfect storm of technologies that are disrupting and transforming classic communications models and ecosystems. In his session at @ThingsExpo, Erik Perotti, Senior Manager of New Ventures on Plantronics’ Innovation team, will provide an overview of this technological shift, including associated business and consumer communications impacts, and opportunities...
SYS-CON Events announced today that iDevices®, the preeminent brand in the connected home industry, will exhibit at SYS-CON's 18th International Cloud Expo® | @ThingsExpo, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. iDevices has announced that it has entered into a definitive agreement to sell the world’s #1 app-enabled grilling and cooking thermometer brands, namely iGrill® and Kitchen Thermometer, to Weber-Stephens Products, LLC. Weber®, the world’s lar...
Latest Stories
Cloud Expo & DevOps Summit 2015 West
KEYNOTES
Intellyx
Opening Keynote | Innovation in the Age of Digital Transformation
IBM
Day 2 Keynote | Geek Girls Are Chic: 5 Career Hacks
Octoblu
Day 3 Keynote | How We Built and Scaled an IoT Platform and Business
POWER PANELS
Cloud Expo Power Panel
Cloud Expo Power Panel | Cloud Computing: We Now Live in an API World
DevOps Summit Power Panel
DevOps Summit Power Panel | DevOps Five Years Later: What Does the Future Hold?
IoT Power Panel
@ThingsExpo Power Panel | The World's Many IoTs: Which Are the Most Important?
Cloud Expo & DevOps Summit 2015 East
KEYNOTES
IBM
Opening Keynote | Geek Girls Are Chic: 5 Career Hacks
Cisco
Day 2 Keynote | The Internet of Everything: Seizing the Opportunities
Virtustream
Day 3 Keynote at 16th Cloud Expo | Rodney Rogers, CEO of Virtustream
VENDOR PRESENTATIONS
Akana
General Session at 16th Cloud Expo | Laura Heritage, Director of API Strategy at Akana
CenturyLink
General Session at 16th Cloud Expo | David Shacochis, Vice President at CenturyLink
Cisco
General Session at 16th Cloud Expo | Paul Maravei, Regional Sales Manager, Hybrid Cloud, Cisco
CodeFutures
General Session at 16th Cloud Expo | Dan Lynn, CEO of CodeFutures Corporation
MetraTech, now part of Ericsson
General Session at 16th Cloud Expo | Esmeralda Swartz, VP, Marketing Enterprise & Cloud at Ericsson
SoftLayer
General Session at 16th Cloud Expo | Phil Jackson, Lead Technology Evangelist at SoftLayer
MetraTech, now part of Ericsson
General Session at 16th Cloud Expo | Esmeralda Swartz, VP, Marketing Enterprise & Cloud at Ericsson
Windstream
General Session at 16th Cloud Expo | Michael Piccininni, EMC, & Mike Dietze, Windstream
POWER PANELS
Cloud Expo Power Panel
Cloud Expo Power Panel | The Evolving Cloud: Where Are We Today?
DevOps Summit Power Panel
DevOps Summit Power Panel | Balancing the Three Pillars of DevOps
IoT Power Panel
@ThingsExpo Power Panel | The Internet of Things: A New Age
Microservices & IoT Power Panel
Microservices & IoT Power Panel at DevOps Summit
VIEW KEYNOTE WEBCASTS
Microsoft
Microsoft Opening Keynote | NoOps != No Operations
Qubell
DevOps Summit Keynote | Purpose-Defined Computing: The Next Frontier in Automation
PLATINUM SPONSORS
Verizon Enterprise
General Session | Verizon Pay-As-You-Go Model for Oracle Database Licenses Means Costs Savings and Business Benefits
Verizon Digital Media Services
Creating a Faster, More Secure Cloud
GOLD SPONSORS
Cisco
General Session | [Podcast] Hybrid Cloud – Different Clouds for Different Needs
SAP
General Session | Innovation with Cloud and Big Data Solutions That Will Revolutionize Your Business – Join SAP and Partners
SoftLayer
General Session | How to Architect and Optimize Your Cloud for Consistent Performance
Power Panels