mercredi 15 mars 2017

Convert from 1.x to Angular 2.0 - Part 2

SERVICES 

Angular 1.x

Angular 2


In Angular 1.x, if we want defining a service we have 5 different ways : Factory,Service, Provider,Constant and Values.

But in Angular 2, we use class that is the only way to define a service.
Example :

Angular 1.x

angular.module('app').service ('ClientService', ClientService);
function ClientService () {
this.getClients = function () { return
      [
        {id: 1, name: 'Hamida'},
        {id: 2, name: 'Mohamed'},
       {id: 3, name: 'Rayen'}
      ];
   }
}

Angular 2

import {Injectable} from '@angular/core';
@injectable()
export class ClientService {
getClients = () => [
      {id: 1, name: 'Hamida'},
      {id: 2, name: 'Mohamed'},
      {id: 3, name: 'Rayen'}
  ];
}
And once defined, you need to register it with your main component using provider.
Notice, @Injectable() is added to service class.

Dependency Injection

One of the advantage of Angular is Dependency Injection (DI). With Angular 2 DI is there but now there is a different way to inject dependencies. As everything is class in Angular, so DI is achieve via constructor.

Registering Services with the Injector

Angular 1.x

angular.module('app').service ('ClientService', ClientService);
function ClientService () {
this.getClients = function () { return
      [
        {id: 1, name: 'Hamida'},
        {id: 2, name: 'Mohamed'},
       {id: 3, name: 'Rayen'}
      ];
   }
}
ClientService ==> REGISTRATION

Angular 2

@NgModule({
imports: [BrowserModule, FormModule],
declarations : [ClientComponent],
providers : [ClientService],
bootstrap :   [ClientComponent],
})
export class AppModule {}

ClientService==> REGISTRATION

Dependency Injection

Angular 1.x

angular.module('app').controller('ClientController', ClientController);
ClientController.$inject = ['ClientService'];
function ClientController (ClientService) {
    var vm= this;
    vm.title = 'services';
    vm.clients = ClientService.getClients();
}

or angular.module('app').controller('ClientController', function (ClientService));

Angular 2

@Component ({
moduleId: module.id,
selector: 'my-clients',
templateUrl: 'client.component.html',
})
export class ClientComponent {
clients = this.clientService.getClients();
constructor(private clientServiceClientService) {}
}

ROUTES

In Angular 1.x, we use $routeProvider.when() to configuring routing. But in Angular 2, @RouteConfig{(...}) is used. ng-view present in Angular 1.x is replaced with <router-outlet>

Angular 1.x

var app = angular
        .module("MyModule", ["ngRoute"])
        .config(function ($routeProvider) { 
            $routeProvider 
              .when("/home", { templateUrl: "home.html", controller: "homeController" })
              .when("/client", { templateUrl: "client.html", controller: "clientController" }) 
        })
       .controller("homeController", function ($scope) {
            $scope.message = "Home Page"; 
        })    
       .controller("clientController", function ($scope) {
             $scope.clients = ["Hamida", "Mohamed", "Rayen"]; 
       }) 

Angular 2

import { Component } from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
import { ClientComponent } from './client/client.component';
import { ClientService } from './Client/Client.service';
 
@Component({
  selector: 'my-app',
  templateUrl: 'app/app.component.html',
  directives: [ROUTER_DIRECTIVES],
  providers: [
    ROUTER_PROVIDERS,
    ClientService
  ]
})
@RouteConfig([
  { path: '/home', name: 'Home', component: HomeComponent, useAsDefault: true },
  { path: '/client', name: 'Client', component: ClientComponent },
])
export class AppComponent { }

We import Routing because it's a separate module.
 And we have more configurations to make routing work, one is adding [ROUTER_DIRECTIVES] as directive and other is to add ROUTER_DIRECTIVES in providers list.

HTML Page is like this :
<ul>
  <li><a [routerLink]="['Home']" href="">Home</a></li>
  <li><a [routerLink]="['Client']" href="">Client</a></li>
</ul>
ng-href is also replaced by [routerLink]
Angular 2 implements webstandards like components and it’s provide better performance than Angular 1.
To RECAP : we have 7 Keys to compare :

Next article will describe more Angular 2 Essentials: Modules, Components, Templates...


0 commentaires:

Enregistrer un commentaire