Tuesday, November 29, 2016

Work with service in Angular2

Conceptually service is independent snippet of code which contains certain functionality or business logic. In Angular2 service is nothing but class of typescript (If we use typescript) which we can inject to component or module.

Yes, we can inject service to both component and module level. In this example we will demonstrate same.

If you are new in Angular2 , I will recommend to go through my previous article to setup angular2 project in IDE.


So, let’s start to implement one simple service which will return list of Person Object.
Add app.dataService.ts file in app folder. Here is content of file.

import {Injectable} from "@angular/core";
export interface Person {
    name: string
}

@Injectable()
export class dataService{
   
    getPerson(): Person[]
    {
        return [
            { name: "Ram" },
            { name: "Syam" },
            { name: "Jodu" }
        ];
    }
}

Here Person interface is type which we are returning from getPerson() function. Please note that the @Injectable decorator is needed when we want to inject to some other unit of code.

Inject service to component

As we said, service can be injectable both to component and module. Here we will inject service to component. Here we have created PersonComponent where we are injecting service in provider section.

import {Component} from '@angular/core';
import {dataService ,Person } from './app.dataservice'
import {OnInit} from "@angular/core";

@Component({
    selector: 'person',
    template: `<ul>
    <li *ngFor="let p of _persons">{{p.name}}</li>
    </ul>`,
    providers: [dataService],
})
export class PersonComponent {

    public _persons: Person[];
    constructor(private _dataService: dataService)
    {
        this._persons = this._dataService.getPerson();
    }

}


In constructor we are consuming getPerson() function which populating _Person member. Now, let’s create a view to display the component. Here is our sample view.

<!DOCTYPE html>
<html>

<head lang="en">
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
   
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
   
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
</head>

<body>
    <person>Loading App...</person>

</body>
</html>


Once we run the application ,we will see that data is showing like this.



Inject service in module

Now, let’s see how we can inject service to module. Here mainModule of application where we are injecting service in provider section.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PersonComponent } from './app.main_component';
import { dataService} from './app.dataservice';

@NgModule({
    imports: [BrowserModule ],
    declarations: [PersonComponent],
    bootstrap: [PersonComponent],
    providers: [dataService]
})
export class mainModule
{

};

Now, we can use the service in PersonComponent without inject it.

import {Component} from '@angular/core';
import {dataService, Person } from './app.dataservice'
import {OnInit} from "@angular/core";

@Component({
    selector: 'person',
    template: `<ul>
    <li *ngFor="let p of _persons">{{p.name}}</li>
    </ul>`
})
export class PersonComponent {

    public _persons: Person[];
    constructor(private _dataService: dataService) {

        this._persons = this._dataService.getPerson();
        console.log(JSON.stringify(this._persons));

    }

}

Monday, November 28, 2016

Main and Feature module in Angular2

We can assume Module as root node in angular2 application. A module may contains components (one or more), pipes, services which is logically related to some module. For example, if we create login module then probably login component, sign in component, logout component will be child of login module. So we can say that those component will hook up with login module. Again, those component may use login service, logout service etc. which again logically related to login functionality and can be inject to login module.

 Point to be noted that each angular2 application should have at least one module which will load in bootstrap to startup the application. We can call the module as main module.
The application may contains many sub module to support business functionality and those module could be call as feature module.

The feature module will attach to main module so that it will be accessible in application. To make available one module to other module we have to export it. The consumer module have to import same to consume it.

In this small example we will learn to attach one feature module to main module. I am assuming that you have Angular2 setup in your editor. If not please follow my previous article for step to step guide of angular setup.


Now, follow the steps to implement same.

The entire folder structure will be like this.


Step1) Create main component.

Create “app.main_component.ts” file under app folder of application.


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


@Component({
    selector: 'welcome',
    template: `<p>{{message}}</p> <login></login>`
})
export class welcomeComponent {
    private message: string;
    constructor() {
        this.message = "Welcome to app."
    }
}

Just notice that we have used “<login></login>” element in template section which is defined in our feature module which we will implement in steps.

Step2) Create main module.

Add main.ts under app folder in application and here is implementation.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { welcomeComponent } from './app.main_component';
import {loginModule} from './app.login_module';

@NgModule({
    imports: [BrowserModule , loginModule],
    declarations: [welcomeComponent],
    bootstrap: [welcomeComponent]
})
export class mainModule
{

};

Just notice that we have imported our feature module called “loginModule” in imports section of main module. The loginModule we will define in short.

Step 3) Setup main module for bootstrap.

Here is code to setup mainModule in bootstrap method. So mainModule will trigger when application will load first time. The file name is “main.ts”

import {platformBrowserDynamic}    from '@angular/platform-browser-dynamic';
import {mainModule} from './app.main_module';
platformBrowserDynamic().bootstrapModule(mainModule);

Step 4) now we will concentrate in feature module

Add “app.login_component” file under app folder.  The loginComponent contains very simple template, We can implement real time login template and handle event in real application.
import {Component} from '@angular/core'

@Component({
    selector: 'login',
    template: '<p> Welcome to login section..</p>'
})
export class loginComponent {

}

Step 5 ) Add login module

Add “app.login_module.ts” file under app folder. The login module is linked with loginComponent. In need we can attach more login/logout related component with this module  

import { NgModule } from '@angular/core';
import {loginComponent } from './app.login_component';
import { CommonModule } from '@angular/common';

@NgModule({
    imports: [CommonModule],
    declarations: [loginComponent],
    exports: [loginComponent]
})
export class loginModule {

};

Step 6) The last step is to create “index.html” page. And set it as startup page.

<!DOCTYPE html>
<html>

<head lang="en">
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
   
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
   
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
</head>

<body>
    <welcome>Loading App...</welcome>

</body>
</html>

Step 7) Run and Fun!!



Saturday, November 26, 2016

Getting started with Angular2 with ASP.NET

This is hello world article we will learn to setup Asngular2 application in ASP.NET Environment. We are using Visual Studio 2015 as IDE. You may use some other but make sure to provide proper setting in “tsconfig.json” file (which we will discuss later on)

 From my personal experience I feel that choosing proper version in angular2 is bit confusing. If you try with beta or RC version some feature may not support. Please make sure to check angular2 version before implementing any new feature.

In this example we are using 2.0.0 version of angular and proper version of dependent components. So let’s start to follow few steps to implement hello world in Angular2.

Step 1) Choose ASP.NET project Template. We could choose ASP.NET Core as well.



Step 2) Add package.json in application. Here is content of package.json file.

{
    "name": "sample app",
    "version": "1.0.0",
    "author": "Sourav Kayal",
    "description": "Just hello World.",
    "scripts": {
        "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
        "tsc": "tsc",
        "tsc:w": "tsc -w",
        "lint": "tslint ./app/**/*.ts -t verbose",
        "lite": "lite-server",
        "typings": "typings",
        "postinstall": "typings install"
    },
    "license": "ISC",
    "dependencies": {
        "@angular/common": "2.0.0",
        "@angular/compiler": "2.0.0",
        "@angular/core": "2.0.0",
        "@angular/forms": "2.0.0",
        "@angular/http": "2.0.0",
        "@angular/platform-browser": "2.0.0",
        "@angular/platform-browser-dynamic": "2.0.0",
        "@angular/router": "3.0.0",
       
        "core-js": "^2.4.1",
        "reflect-metadata": "^0.1.3",
        "rxjs": "5.0.0-beta.12",
        "systemjs": "0.19.27",
        "zone.js": "^0.6.23",
        
        "bootstrap": "^3.3.6"
    },
    "devDependencies": {
        "concurrently": "^2.2.0",
        "lite-server": "^2.2.0",
        "tslint": "^3.7.4",
        "typescript": "^2.0.2",
        "typings": "^1.0.4"
    },
    "repository": {}
}

Step 2) Add tsconfig.json file and here is content.

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules",
    "wwwroot",
    "Scripts/app"
  ]

}

The exclude section of this file depends on the IDE where you are developing application. In case of Visual Studio 2015 the setting is like this.

Step 3 ) Add systemjs.config.js file in application and here is the content
/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

      // other libraries
      'rxjs': 'npm:rxjs'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

In app sub section under packages we have referred main.js file. Which indicates that this file is our entry point of application and load first.

 Step 4) Add typings.json file with this content

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "node": "registry:dt/node#6.0.0+20160831021119"
  }
}

Here we have complete our environment setup for Angular2. Now we will concentrate on Application setup.

Step 5) Add app.component.ts under app folder and add below content.

import {Component} from '@angular/core';
@Component({
    selector: 'my-app',
    template: '<h1>Hello World :)</h1>'
})
export class AppComponent { }

Step 6) Add app.module.ts file under app folder with below content.

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

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

export class AppModule { };

Step7) Add main.ts file under app folder with below content

import {platformBrowserDynamic}    from '@angular/platform-browser-dynamic';
import {AppModule} from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

So the entire directory structure will look like this




Step 8) Add index.html page in application. Here is content of same.

<!DOCTYPE html>
<html>

<head lang="en">
    <base href="/">
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

   
    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
   
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
   
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
</head>

<body>
    <my-app>Welcome.

</my-app>
</body>

</html>


Step 9) Hit F5 and Cheers!!!



PS : Please do not change file name anywhere if you are not aware of subsequent following change. This just hello world guide in Angular2. To understand meaning of code and execution sequence please follow any good tutorial.

Please follow this tutorial to learn basic of Angular2