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...


Related Posts:

  • Retrospective 2016 - Scrum way - Part 1 Why ? The answer is simple : “To change for the better”. Should be Agile not only in our work but in our life ? The answer : Yes ! Tell me how ? When we start a new project with a Product Owner, we focus on the fu… Read More
  • Build persisting Layer with ASP.NET Core and EF Core using Postgresql and Sql Server 2016 Build persisting Layer with ASP.NET Core and EF Core using Postgresql and Sql Server 2016 Source :  https://github.com/didourebai/Samples.AspCoreEF This post is about developing ASP.NET Core application using E… Read More
  • Minecraft Hour of Code Trying coding in early age, when we are child can give him/her the opportunity to work in logic parts, some kind of games can let you discover if the child is able to think and decide. We started this in some schools but… Read More
  • NLayered Architecture When we start any project,  we have to think about the architecture and use the best practices and avoid the anti-pattern (http://hamidarebai.blogspot.it/2016/03/do-you-like-spaghetti-or-lasagna.html) ,  To ach… Read More
  • Start with Azure Blob storage using Web API Overview Azure Blob Storage is part of the Microsoft Azure Storage service that is able to  stores unstructured data in the cloud as objects/blobs.  Blob storage s a collection of binary data&n… Read More

0 commentaires:

Enregistrer un commentaire