Welcome!

Open Source Cloud Authors: Elizabeth White, Liz McMillan, Wesley Coelho, Rainer Ersch, Yeshim Deniz

Related Topics: @DevOpsSummit, Java IoT, Linux Containers, Open Source Cloud, Agile Computing, @CloudExpo, @BigDataExpo, @ThingsExpo

@DevOpsSummit: Blog Feed Post

Angular 2 and TypeScript | @ThingsExpo @YFain #IoT #JavaScript #TypeScript

Now let’s take a quick glance at Angular 2, a complete re-write of the popular open-source framework managed by Google

Why Java Developers Will Embrace Angular 2 and TypeScript

Most of the Java developers I know don’t like JavaScript. Initially. They would give you different reasons why, but the real one is simple: too much to learn to make it work. For many Java developers creating the front end of a Web application in JavaScript is a chore to write and a burden to maintain. Nevertheless JavaScript rules in Web development and the new version of JavaScript (ES6) will make it even more popular.

ES6 offers classes, standardized module definition, arrow expressions (lambdas), predictable “this” and a lot more. Firefox and Chrome already support most of the ES6 syntax, and other browsers are getting there as well.

But there is something better than ES6: the TypeScript language, which has most of what ES6 has to offer plus types, casting, interfaces, generics, and annotations. The TypeScript code analyzer will help you to see syntax errors even before you run the program. Code refactoring works as well. In this blog I stated the main reasons of why TypeScript is the right way for JavaScript development.

Now let’s take a quick glance at Angular 2, a complete re-write of the popular open source framework managed by Google. Angular 2 is currently in Beta.0 and it’s safe to start using it for your next Web project unless your app has to go to prod in the first half of 2016. Angular 2 is stable enough for serious development, and I know this firsthand after surviving a couple of dozens of alpha releases of Angular 2.

Disclaimer. You can write Angular applications in the current JavaScript (ES5), next JavaScript (ES6), Dart, or TypeScript. Based on my experience with all these languages using TypeScript is the best option.

What makes the Angular 2/TypeScript combo so appealing to Java folks?
First of all, the code looks clean and easy to understand. Let’s do an experiment. I’ll give you a two-paragraph intro on how to write an Angular component in TypeScript followed by the sample code. See if you can understand this code.

Any Angular application is a hierarchy of components represented by annotated classes. The annotation @Component contains the property template that declares an HTML fragment to render 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 HTML from the @Component section and are implemented as the class methods.

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 lesson is over.

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

@Component({
selector: 'search-product',
template:
`<div>
<input #prod>
<button (click)="findProduct(prod.value)">Find Product</button>
Product name: {{product.name}}
</div>
`
})
class SearchComponent {

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

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

A Java developer can read and understand most of this code right away. Okay, okay. I’ll give you more explanations. 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 is a local template variable that stores a reference to the input field 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 field.

Note that the HTML template is surrounded with the back tick symbols, which allows you to write the markup in multiple lines in a readable form. If you prefer to store HTML in a separate file instead of `template` use the `templateURL` property:

templateUrl: './search.html'

Dependency Injection. Angular architecture will be very familiar to those who use Spring framework or Java EE. Angular comes with the Dependency Injection (DI) module, which instantiates an object using a registered class or a factory and injects it to the application component via constructor’s arguments. The following code will instruct Angular to instantiate the class ProductService and inject it into the ProductComponent:

@Component({
providers: [ProductService]
})
class ProductComponent {
product: Product;

constructor(productService: ProductService) {

this.product = productService.getProduct();
}
}

Specifying the provider and declaring the constructor with the type is all you need for injecting the object. Application components form a hierarchy, and each component may have its own injector. Injectors are not singletons.

App structure. The following image shows what the main page of a sample application is made up of. The parent component includes child components, which are surrounded with green borders.

ch2_auction_home_page_components

Router. Angular shines if you need to develop a single-page application (SPA), where the entire Web page is never reloaded. Angular router allows you to easily configure the page fragments (the views) that should be loaded based on the user’s actions. The code snippet below includes the annotation @RouteConfig that configures two routes Home and ProductDetail, which are mapped to the corresponding components (HomeComponent and ProductDetailComponent). The user navigates the application by clicking on the links with the corresponding routerLink attribute, which will display the requested component in the area marked as <router-outlet>.

@Component({
selector: 'basic-routing',
template: `<a [routerLink]="['/Home']">Home</a>
<a [routerLink]="['/ProductDetail']">Product Details</a>
<router-outlet></router-outlet>`,
directives: [ ROUTER_DIRECTIVES]
})

@RouteConfig([
{path: '/', component: HomeComponent, as: 'Home'},
{path: '/product', component: ProductDetailComponent, as: 'ProductDetail'}
])
class RootComponent{
}

Inter-component communication. Each component in Angular is well encapsulated, and you can create it in a losely-coupled manner. To pass the data from the outside world to the component just annotate a class variable(s) with @Input() and bind some value to it from the parent component.

class OrderComponent {

@Input() stockSymbol: string;
@Input() quantity: number;
}

To pass the data from the component to the outside world, use the @Output annotation and dispatch events through this variable. Dispatch to whom? Ain’t none of the component’s business. Let’s whoever is interested listen to this event, which can be either a standard or a custom event carrying a payload.

class PriceQuoterComponent {
@Output() lastPrice: EventEmitter<IPriceQuote> = new EventEmitter();
...
}

See something familiar? You got it. That thingy in the angle brackets after EventEmitter the type denotes a generic type, and IPriceQuote can be an interface. TypeScript supports generic and interfaces.

Casting. Since TypeScript supports classes and interfaces (class A extends B implements D, E, F) it should support casting, and it does. As in Java, upcasting doesn’t require special notation. To denote downcasting surround the target type with angle brackets and place it before more general type as shown in the screenshot below.

casting

I took this screenshow while after placing the cursor before value in line 17. I use WebStorm 12 IDE (a little brother of IntelliJ IDEA), which supports TypeScript quite nicely (including refactoring), and this supports improves with every minor release of WebStorm. If I wouldn’t declare the variable with the type in line 15 and wouldn’t use casting, the code would still work, but the IDE would show value in red and the code completion wouldn’t work in line 17.

Streams and lambdas. These are big in Java 8. Angular 2 incorporates RxJS, the library with react extensions, where streams is a religion. Everything is a stream in RxJS, and Angular 2 promotes using observable streams and subscribers.
Even events are streams, can you believe this? The user types in an HTML input field or is dragging the mouse, which generates a stream that you can subscribe to (think observer/observable or pub/sub).

Make an HTTP request or open a WebSocket and subscribe to the observable stream, which is a Promise on steroids. Handling results is still an asynchronous operation, but as opposed to a Promise it can be cancelled.

In Java 8 you can run a stream through a number of changed intermediate operations (e.g. map()) followed by a terminal one. In Angular 2 you can do the same:

class AppComponent {

products: Array = [];

constructor(private http: Http) {

this.http.get('/products')
.map(res =>; res.json())
.subscribe(
data => {
if (Array.isArray(data)){
this.products=data;
} else{
this.products.push(data);
}
},
err =>
console.log("Can't get products. Error code: %s, URL: %s ", err.status, err.url), () => console.log('Product(s) are retrieved')
);
}
}

If the above code requires explanations, then your Java is a little rusty. Seriously.

Module loading. One of the important features that ES6 brings to Web development is standardization of module loading. The application code consists of modules (typically one module is one script file). Using the export keyword (e.g. export class Product {...}) you specify which members of the module should be exposed to other scripts. Accordingly, a script can include one or more import statements to have access to other modules.

ES6 includes the syntax for importing/exporting modules, but the standardization of the module loader System is postponed, and we use the polyfill SystemJS that can load modules of all existing formats (including ES6). When the System object will become standard in all browsers that support ES6, you won’t need to change your code (removing the polyfill is all that’s needed).

The main HTML file of he Angular/TypeScript application simply includes the configuration of the loader and transpiler (the running code must be compiled to JavaScript) and import statement of the main application component:

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

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

In the above code snippet the System object imports the module from the file app.ts, which is a root component of the application and may have child components represented by custom HTML tags. The System loader reads all import statements in each application component and loads all dependencies accordingly. Lazy loading of the modules is supported as well.

Deployment. Java developers use build tools like Maven or Gradle for deployment. Guess what, Angular developers use them as well. The TypeScript code needs to be transpiled into JavaScript, minimized and obfuscated before deployment to QA or prod servers. Some people use Grunt, some Gulp, but we use Webpack for bundling the code and npm scripts for deployment. The jury is still out on the best build automation tools, and we keep our eyes open.

I hope that after reading this blog thousands (ok, hundreds) of Java developers will decide to take a closer look at Angular 2. Start with Angular architecture.

In this blog I showed you just a tip of the iceberg. You’d need to invest some time in learning Angular 2 and TypeScript, but the learning process isn’t too steep for Java folks. If you want to make this process as pleasant as it can be, get the book that I’m co-authoring or enroll in one of our training classes.

IMHO Angular 2 will make as big of an impact in the JavaScript community as Spring Framework has in the Java world.

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

@ThingsExpo Stories
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
"We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
The financial services market is one of the most data-driven industries in the world, yet it’s bogged down by legacy CPU technologies that simply can’t keep up with the task of querying and visualizing billions of records. In his session at 20th Cloud Expo, Karthik Lalithraj, a Principal Solutions Architect at Kinetica, discussed how the advent of advanced in-database analytics on the GPU makes it possible to run sophisticated data science workloads on the same database that is housing the rich...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, has been named "Bronze Sponsor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that EnterpriseTech has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effic...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that Cloud Academy named "Bronze Sponsor" of 21st International Cloud Expo which will take place October 31 - November 2, 2017 at the Santa Clara Convention Center in Santa Clara, CA. Cloud Academy is the industry’s most innovative, vendor-neutral cloud technology training platform. Cloud Academy provides continuous learning solutions for individuals and enterprise teams for Amazon Web Services, Microsoft Azure, Google Cloud Platform, and the most popular cloud com...
SYS-CON Events announced today that Cloudistics, an on-premises cloud computing company, has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cloudistics delivers a complete public cloud experience with composable on-premises infrastructures to medium and large enterprises. Its software-defined technology natively converges network, storage, compute, virtualization, and ...
SYS-CON Events announced today that CHEETAH Training & Innovation will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CHEETAH Training & Innovation is a cloud consulting and IT training firm specializing in improving clients cloud strategies and infrastructures for medium to large companies.
SYS-CON Events announced today that Datanami has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datanami is a communication channel dedicated to providing insight, analysis and up-to-the-minute information about emerging trends and solutions in Big Data. The publication sheds light on all cutting-edge technologies including networking, storage and applications, and thei...