Archive

Archive for November, 2017

Angular 5.0 New things

Angular team has released Angular 5.0 on 1st Nov 2017.

They focused on most new features and bug fixes. This release continues our focus on making Angular smaller, faster, and easier to use.

Following things are New:

Angular CLI 1.5 and Angular 5.0.0

Now we are in CLI 1.5, if you install CLI 5.0, automatically you will get the angular 5.0 versions default in your package.json file in angular app.

 Typescript updated  to 2.4

Dynamic import expressions are a new feature and part of ECMAScript that allows users to asynchronously request a module at any arbitrary point in your program.

RXJS was updated to 5.5 version:

This recent release of RxJS fully empowers developers to avoid the side effects of the

previous import mechanism with a new way of using RxJS called “lettable operators”.

These new operators eliminate the side effects and the code splitting .

Tree shaking problems that existed with the previous ‘patch’ method of importing operators.

instead of :

import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';

import 'rxjs/add/operator/filter';

names = allUserData

.map(user => user.name)

.filter(name => name);

user below like this:

import { Observable } from 'rxjs/Observable';

import { map, filter } from 'rxjs/operators';

names = allUserData.pipe(

map(user => user.name),

filter(name => name),

);

Buid optimizes.,Bundle size reduced, Speed the app

Ahead -of -time compiler

Converts your angular code before browser downloads and run it

Aot:  faster rendering . few async reauests, smaller download

watch mode files ngc –watch. This command will watch your file what are the file executing

Easier to build progressvie web apps

The build optimizer does is to remove Angular decorators from your application’s runtime code. Decorators are used by the compiler, and aren’t needed at runtime and can be removed. Each of these jobs decreases the size of your JavaScript bundles, and increases the boot speed of your application for your users.

Their goal is to make this angular default option for most developers

->service workers

->small, easier and more powerfull

->Http client module feature added.  from

import { HttpClientModule } from '@angular/common/http';

removed map(res=> res.jon()) calls which no longer needed with http client module.

depreacted http in 5.0 version,  for now you can use http in 5.0 but its depreacted. In future they may removed from angular 5.0

Angular Form validation

They added some new feature on forms.

angular 4 form validates the form when we entered the characters.

but in angular 5 they inclueded validation on blur and submit

validation and value updates on `blur` or on `submit`, instead of on every input event

Template Driven Forms

Before

<input name="firstName" ngModel>

After

<input name="firstName" ngModel [ngModelOptions]={updateOn: 'blur'}>

OR

Validations will be done on submit.

Or you can add for each individual with ngModel options

<input name ="firstName" ngModel[ngModelOptions]={updateOn: 'blur'}>

Or simply you can use the reactive forms

Reactive Forms

Before

new FormGroup(value);

new FormControl(value, [], [myValidator])

After

new FormGroup(value, {updateOn: 'blur'}));

new FormControl(value, {updateOn: 'blur', asyncValidators: [myValidator]})

Changes with pipes

DepreactedI 18 Npipes module

old pipes will depreacted but you can use now. In future they may removed from angular 5.0

Increase standardization across browsers

Internationalized Number, Date & Currency

Router Life cycle Events:

New lifecycle events to the router, allowing developers to track the cycle of the router from the start

of running guards through to completion of activation. These events could be used for things such as showing a spinner on a specific router outlet when a child is updating or to measure performance of guards and/or resolvers. Allow develpers to track the routing cycle used to do things like show spinners, measures performance of guards

GuardsCheckStart, ChildActivationStart, ActivationStart, GuardsCheckEnd, ResolveStart, Resolve End,

ActivatonEnd, ChildActivationEnd

An example of using these events to start/stop a spinner might look like this:

class MyComponent {

constructor(public router: Router, spinner: Spinner) {

router.events.subscribe(e => {

if (e instanceof ChildActivationStart) {

spinner.start(e.route);

} else if (e instanceof ChildActivationEnd) {

spinner.end(e.route);

}

});

}

}

Angular Universal State Transfer API and DOM Support

Easily share application state between the server side and client side versions of your application.

And helping developers to perform  server side rendering (SSR) of Angular applications.

By rendering your Angular applications on the server and then bootstrapping on top of the generated HTML, you can add support for scrapers and crawlers that don’t

Support JavaScript, and you can increase the perceived performance of your application.

In 5.0.0, the team has added ServerTransferStateModule and the corresponding BrowserTransferStateModule. This module allows you to generate information as part of your rendering with platform-server, and then transfer it to the client side so that this information does not need to be regenerated

This means when you fetch the data over http, by transfer data from there server, this means developers no need to make 2nd HTTP request

It supported more DOM manipulations out of the box within server side contexts, improving our support for 3rd party JS and Component libraries that aren’t server-side aware

Improvements on compiler:

They improved compiler to supports incremental compilation. Its provide faster rebuilds,

It builds with AOT, and added new feature to Decorators. And made it possible to smaller bundles

By remove the whitespaces.

Typescript Transforms

Typescript transform, making incremental rebuilds dramatically faster

You can take advantage of this by running ng serve with the AOT flag turned on.

You can take advantage of this by running ng serve with the AOT flag turned on.

ng serve –aot

This will become the default in a future release of the CLI

On this transforms, we don’t need a genDir anymore, and outDir has been changed: we are now always emitting generated files for packages in node_modules.

Preserve Whitespace

Tabs, newlines, and spaces in your templates are recreated and included in the build by the compiler.

You can now choose whether or not to preserve whitespace coming from your components and your application.
1) You can specify this as part of each component’s decorator, where it currently defaults to true.

@Component({

templateUrl: 'about.component.html',

preserveWhitespaces: false

}

export class AboutComponent {}

2) specify in tsconfig.json file also: by default its true.

{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
"module": "es2015",
"types": []
},
"angularCompilerOptions": {
"preserveWhitespaces": false
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}

Decorator Support :

Expression lowering in decorators for lambdas and the value of useValue, useFactory and data in object literals. This allows you to use values that can only be calculated at runtime in decorators for expressions that are lowered.

You can now use a lambda instead of a named function, meaning you can execute code without affecting your d.ts or your public API.

Component({

provider: [{provide: SOME_TOKEN, useFactory: () => null}]

})

export class MyClass {}

-> lower expressions as part of useValue.

Component({

provider: [{provide: SOME_TOKEN, useValue: SomeEnum.OK}]

})

export class MyClass {}

Replace the ReflectiveInjector with StaticInjector

In order to remove even more polyfills, we’ve replaced the ReflectiveInjector with the StaticInjector.

This injector no longer requires the Reflect polyfill, reducing application size for most developers.

Before

ReflectiveInjector.resolveAndCreate(providers);

After

Injector.create(providers);

Please refer angular blog for more info:

https://blog.angular.io/version-5-0-0-of-angular-now-available-37e414935ced

update to angular 5.0 from this below site

If you want to update your angular app to 5.0, just go to below website and give your current version in the fields.

https://angular-update-guide.firebaseapp.com/

Categories: Angular

Java – HashMap in-detail explanation

HashMap works based on hashing algorithm, As per Java doc HashMap has below four constructors,

Constructor Description
HashMap​()
Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
HashMap​(int initialCapacity)
Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).
HashMap​(int initialCapacity,
float loadFactor)
Constructs an empty HashMap with the specified initial capacity and load factor.
HashMap​(Map<? extends K,? extends V> m)
Constructs a new HashMap with the same mappings as the specified Map.

Let’s write simple java program, to examine how Map works internally

  1. Create a simple Map and add one key and value to it

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

map.put(1, "Java");

}

We just created Simple Map, which takes key as Integer and Value as String, and added “1” as Key and “Java” as value. By using eclipse debug feature, lets see what’s inside the map

HashMap-one

It created 16 blocks(0-15) and inserted 1st block with key as Integer “1” and Value as String “Java”. Please check the red box, rest all boxes initialized with  null.

2. Add second key and value to the same map

public static void main(String[] args) {

Map<Integer, String> map = new HashMap<>();

map.put(1, "Java");

map.put(2, "Angular");

}

lets see the map in eclipse debug again

HashMap-two

Now the map contains two keys (1,2) and two values (“Java”, “Angular”) as expected, but the keys are added exactly at 1st block and 2nd block respectively, why?

because as we know Map works based on hashing algorithm, whenever we insert key to map, it calls the Object#hashcode() method, based on the value of hashCode(), it will insert the key into that block.

In above case, Integer class overrides the hashCode with its primitive int value, thats why (1,java) got stored in 1st block and (2,Angular) got store in 2nd block.

3. Lets do the same experiment with our own Class

Create a simple Employee class like below

private static class Employee{
int id;
String name;

Employee(int id, String name){
this.id = id;
this.name = name;
}
}

Use this class as Key to the map and examine the same way


public static void main(String[] args) {
Map<Employee, String> map = new HashMap<>(10);
map.put(new Employee(1, "Ramesh"), "Java");
map.put(new Employee(2, "Sathish"), "Angular");
}

We have added two keys as Employee objects and Values as just strings, lets see in which block the keys got stored this time

HashMap-three

This time, it stored in 8th block and 14th block(why? simple answer because of hashCode of Employee objects), to confirm this, lets override hashCode() of Employee to constant value and check the map. If our analysis correct it has to store all the key’s in the same block.

Update Employee class accordingly

private static class Employee{
int id;
String name;
Employee(int id, String name){
this.id = id;
this.name = name;
}
@Override
public int hashCode() {
return 10;
}
}

We dont need to change anything to our map, lets see now where the keys got stored

HashMap-four

Yes, only 10th block got filled with two objects, why? because both employee objects returned the same hashCode (i.e 10). But how does Map recognized those two objects are not duplicate? As we know internally Map#Key is an entrySet(java.util.Set) it called equals method to verify whether the key is duplicate or not.

While retrieving the value from Map also, first it will check the hashCode of the given key and based on that it will go to that block, after finding the block it will call equals() to get the exact value.

So overriding the hashCode() to constant is not at all recommendable. and when we override the hashCode() we should not forget to override the equals() method as well(i.e hashCode()/equals() contract).

 

 

Categories: Java

Angular 4: Service example

Welcome to Angular 4 services

Angular services are for building out code that can be shared across multiple components. And these are singletons. services restrict the instantiation of a class to one object. It means the methods and properties can be shared throughout your application from a single shared instance.

These services are best way to store the session data and perfect place to call the web services. And the data is shared to the components with the injecting service. Without hitting the web services we can use the session data in the application. But If you refresh the browser the session service data will be empty. So remember that condition.

In this tutorial, we provide a basic angular 4 service example using the Angular CLI.

We’ll be using the Angular CLI to create our app. Create a new Angular project by running:

ng new AngularServiceEx

This will create the new project named as AngularServiceEx project.

And navigate to root application by cd  AngularServiceEx. And run the below command

npm install

This command will download all your dependencies from your package.json file.

And run the below command to create the service in the project.

ng g service reference

It will create the reference.service in the ’app’ folder automatically. We don’t need to do anything.  It will create the two files in our Angular app

  • a reference.service.tsfile under the src/app directory
  • a reference.service.spec.tsfile under the src/app directory

We will write the service code in the service.ts file.  And service.spec.ts file will used for unit testing.

The ng g service command won’t automatically configure your root module app.module.ts to provide the service.

Services must import the Injectable from the angular/core package, like below. see the angular. io website for more info on services.

import { Injectable } from ‘@angular/core’; 

And services uses the  injectable decorator. @Injectable() . The @Injectable decorator simply provides dependency injection for the service.

Don’t forget to add the decorator in the service.ts file. If we don’t add it will not work.

Service must have the export keyword.  Everything like class or component should use ‘export’  keyword. Then only it is possible to use the class or component or anything in the project. And service name should end with .service.  For ex:  reference.service.ts file. If we have lengthy name we need add the ‘–‘ in the service name. That is for code readability.

Example: save-user-info.service.ts

Service structure:

 import { Injectable } from '@angular/core';

@Injectable()

export class ReferenceService {

constructor() {  console.log(“welcome! Reference Service”);  }

}} 

To include the service in your app, you must import it and include it as a provider in app.module.ts or we can add the service in providers of component meta data also. But it will be available in the particular component only. But it’s better to use the service in the providers of app.module.ts. Service will create the instance every time, whenever you come to the component.  By registering the service as a provider, you make it available everywhere in the application.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ReferenceService } from './reference.service'

@NgModule({
declarations: [ AppComponent ],
imports: [ BrowserModule ],
providers: [ReferenceService],
bootstrap: [AppComponent]
})

export class AppModule { }

Accessing the Service from a component:

app.component.ts

Services must be imported by the component. We will import our reference service in open the auto-generated app.component.ts and replace it with the following:

import { Component } from '@angular/core';
import { ReferenceService } from './reference.service'

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent {
constructor(public reference: ReferenceService){

}
}

Service with HTTP methods :

We will have to interact with Database to get the data and post the data. For that we will write the web service api in the Angular services. We will have to call the HTTP POST or HTTP GET methods with REST API in the service to store that data in the DATABASE or retrieve the data from the DATABASE.

Let’s see the Example with real Json file:

We will use the Reference Service. And we will write the http method in the reference service. That http method should be called in the component methods to get the data or post the data to the REST side. For now will go through with angular services with Json file.Will add one json file in the project. In the angular every request and response will be in the Json  only. You need to add the json file in the assets folder under src folder of your project. You may get 404 json file not found, if you add the json file somewhere other than assets location folder.

Json file:

Created the json folder in the assets folder in ‘src/assets’. See example json data.


[

{ “id”: 10, "firstName": "Sathish" , "lastName": "Kotha" },

{ “id”: 11, "firstName": "Ramesh", "lastName": "Kotha" },

{ “id”: 12, "firstName": "Ragav" , "lastName": "Raju" }

]

Employee class:

We need to create the Employee model class. It’s a type of json data, remember every where we need export the class. This model class is a typescript format. Type the below command.

ng g class Employee

This will create the Employee model class in the app folder.

typically you declare types in a model which can then be reused throughout the rest of the application. With TypeScript, frontend applications can now benefit from strongly typed models!

This is pretty straightforward for declaring individual variables,

A simple example of this is a Employee class that defines a firstName and lastName variables that’s are string and an id variable that must be a number:

export class Employee  {

id: number;

firstName: string;

lastName: string;

}

Service:

In the service, we will  import the Http from “@angular/http”; with http we will use the http get the post and request methods. To get the all the methods we need to include the http in the constructor. for more info on http please refer https://angular.io/tutorial/toh-pt6

And import some rxjs. These are reactive extension java script. Rxjs is a reactive streams library that allows you to work with asynchronous data streams. RxJS can be used both in the browser or in the server-side using Node.js. We will use some methods from the Rxjs in angular services like map and observable and catch. We will use these in the services.

Don’t instantiated the service with new keyword, it will create error prone and memory leak.

import { Injectable } from '@angular/core';

import { Http } from '@angular/http';

import 'rxjs/add/operator/map';

import 'rxjs/add/operator/catch';

import { Observable } from 'rxjs/Observable';

import { Employee } from './employee';

@Injectable()

export class ReferenceService {

constructor(private http: Http) { }

getAllEmployees(): Observable< Employee[] > {

try {

return this.http.get(‘assets/service.json') .map(this.extractdata).catch(this.handleerror) ;

// Api Full path like, http://localhost:4200/assets/service.json

}   catch (error) { console.log(error); }  }

extractData(res: Response) {

const body = res.json();

return body || {};   }

handleError(error: any) { return Observable.throw(error); }
}

In the above service  http reference is used to call the http methods. We created one method is get all employees, we are calling http.get method with json link. This get method will get the json data. Then it will come to  map method, it is used to extract the JSON content from the response coming as the observable type. if you got any error while calling the http method it will come to catch method,from there it will directly throw the error with observable throw method.

Component:

Import the reference service in the component as below and one more thing we need the ngOn Init life cycle method. Every component has to implement the ngOnInit method. And this method will call after the constructor. It’s used like a main method. When you come to component, ng On Init method will call, you can call any number of methods in the ngOnInit method.

import { Component, OnInit } from '@angular/core';

import { ReferenceService } from './reference.service';

import { Employee } from './employee';

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']  })

export class AppComponent implements OnInit  {

title = 'Angular Service app';

employeesInfo: any;

constructor(public referService: ReferenceService) { }

getAllEmployeesInfo() {

this.referService.getAllEmployees() .subscribe((result: Employee[]) => {

console.log('the employess data:' + result);

this.employeesInfo = result;      },

(error: any) => {  console.log('error in employees method');      });   }

ngOnInit() {  this. getAllEmployeesInfo();  }

}

In above component, service method is called in component method getAllEmployeesInfo with reference service http method. And when we got the output it will come to subscribe result.  There we are assigning the result to our variables. If we get any error when calling the api it will come to error block. This error will return from catch of Observable  throw error.

App.component.html:

<h1 style="text-align: center">  Welcome to {{title}}!</h1>
<h3  style="text-align: center">ALL employeesInfo here</h3>
<div style="text-align: center;">
<div *ngFor="let emp of employeesInfo">
<b>Emp ID</b> {{emp.id}}

<b>  First Name is :</b> {{emp.firstName}}

<b>Last Name is :</b> {{emp.lastName}}</div>
</div>

Above html we are using title in curly brackets. It’s a two way bindings. Whatever we add it automatically convert the value. And one more new word is “*ngFor” structural directives. This is used to iterate the json data in the html. We have the multiple employes the data in the “ employessInfo”  variable. So we need to include the ng for here to iterate the data in the html. We add the reference value in the ng for. With that will call the inside object data.

Service used in the Module:

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

import { ReferenceService } from './services/reference.service';

@NgModule({

declarations: [ AppComponent ],

imports: [ BrowserModule, HttpModule ],

providers: [ReferenceService],

bootstrap: [AppComponent] })

export class AppModule { }

Above app.module we have imported reference service and app component , All components should be added in the declarations field. And service should go to provides. Httmodule is also imported to imports. And last app component will be added in the bootstrap , bootstrap will added to project from here

if you don’t add the service in the providers you will get following error. One more thing we need to add the http module in the app module imports. Don’t add the http in the imports. If you don’t include. You will get below error.

EXCEPTION: No provider for service!

Clone the repository and install all it’s dependencies:

# Clone repo

git clone https://github.com/Sathishchary/AngularServiceEx

# Enter into directory

cd AngularServiceEx

# Install dependencies

npm install

Categories: Angular