Categories: Angular 2

Complete Migration guide from Angularjs To Angular2

Angular 2.0 is a complete is a total revise of Angular 1.x, This brings up the issue of what to do with our “old” Angular 1.x applications .

Building the same applications from scratch is sometimes impossible due to time and priority constraints. Therefore, the Angular team has come with a way to enable us with the incremental migration of our application.

The Angular 1.x styleguide is widely explained at the following address:https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md

How to start

Using module loader

Since Angular 2.0 uses a module loader built in, your migration will be much easier if you use a module loader now. You may have your tsconfig.json file for your Angular 2.0 application set to use the same module loader.

Typescriptify your code

Suprising as it sounds, this task is not so hard. Typescript is in fact a superset of JavaScript, so with a little change you will be able to have your Angular 1.x application built with TypeScript.

Asumming you are familiar with tsc and with the tsconfig.json file, all you need to do is to implement them in your Angular 1.x application. You may just change the file extension of each .js file to .ts and try to compile it.

However, after doing so, you may want to use Typescript features and not just change the extension. Let’s see what you can do.

  1. Each controller, service, component, directive etc. can be a Typescript class.
  2. Each prototype member can be a class method.
  3. On services, each method assigned as a member on the service instance may be a class method.
  4. A component’s controller (Angular 1.5) may be a class itself.
  5. Its prototype members are class members, and the same as controllers and services.
  6. Precede the Every class with the Export keyword so you will be able to import it later on.
  7. If you already use a module loader, set your Typescript compiler to use it (in tsconfig.json), and now you may use the Typescript import keyword whenever you need.
  8. You need also to install the Angular 1.x type definition, along with the jQuery type definition and Angular route type definition. You may machine all of these by running the following command:
npm run typings install dt~jquery dt~angular dt~angular-route 
dt~angular-resource dt~angular-mocks dt~angular-animate 
dt~jasmine -- --save --global

For example, let’s see how we can alter a controller code.

(function(angular){
function DashboardController(socketControll, dataService) {
this._socketControll = socketControll;
this._data = dataService;
this.users = _data.users;
_socketControl.validateAndOpenListeners();
}
}
angular.module('dunebookexample-app.dashboard',['dunebookexample-app.scocketControll', 'dunebookexample-app.dataService']).controller('dashBoardController',['socketControllService', 'dataService',DashboardController]);
}(window.angular));

Now after Typescript migration:

(function(angular){
class DashboardController{
users: any;
_socketControll: any;
_data: any;
constructor(socketControll, dataService) {
this._socketControll = socketControll;
this._data = dataService;
this.users = _data.users;
_socketControl.validateAndOpenListeners();
}
}
angular.module('dunebookexample-app.dashboard',['dunebookexample-app.scocketControll', 'dunebookexample-app.dataService']).controller('dashBoardController',
['socketControllService', 'dataService',DashboardController]);
}(window.angular));

Let’s have a look at a service:

(function(angular){
function DataService(api){
this._api = api;
}
DataService.prototype.getAllData = getAllData;
DataService.prototype.getUsers = getUsers;
function getAllData() {
return Promise.all([this.getRooms(), this.getUsers()])
}
function getRooms() {
return this._api.send('getRooms').then(function(res)
{
this.rooms = res.data;
});
}
function getUsers() {
return this._api.send('getUsers').then(function(res)
{
this.users = res.data;
});
}
angular.module('dunebookexample-app.services.dataService',
['dunebookexample-app.services.apiService']).service('dunebookexample-app.dataService',
['adge-app.apiService', DataService]);
}(window.angular));

Now, let’s migrate this to Typescript:

(function(angular){
class DataService {
constructor(
private _api: any
) {}
public rooms: any;
public users: any;
getAllData() {
return Promise.all([this.getRooms(), this.getUsers()])
}
getRooms() {
return new Promise((resolve, reject) => {
this._api.send('getRooms').subscribe(
res => {
this.rooms = res.data;
resolve(res)
},
err => reject(err)
)
})
}
getUsers() {
return new Promise((resolve, reject) => {
this._api.send('getUsers').subscribe(
res => {
this.users = res.data;
resolve(res)
},
err => reject(err)
)
})
}
}
angular.module('dunebookexample-app.services.dataService',
['dunebookexample-app.services.apiService']).service('dunebookexample-app.dataService',
['adge-app.apiService', DataService])
;
}(window.angular));

Lets Complete The migration Process

Migrating

In this section we will actually blend in the Angular 2.0 boilerplate to have an Angular 2.0 application. Then we will use the UpgradeAdapter from the ‘@angular/upgrade’ module.

We will add Angular 2.0 packages to our project, the same ones that are in our chat application. We will also add the system.config.js file to our project. This will not affect our Angular 1.x applcation, yet.

Using UpgradeAdapter

The UpgradeAdapter class is the class that will help blend Angular 1.x and Angular 2.0 into one application built on both foundations. We will do it by bootstrapping our application in a slightly different way.

You may have used the ng-app directive on your HTML file, or the angular.boostrap method. To bootstrap the Angular 1.x application so it can work with Angular 2.0, we must in our main.ts file create an instance of the UpgradeAdapter.

With that instance, we will bootstrap our application module:

let upgradeAdapter = new UpgradeAdapter();

upgradeAdapter.bootstrap(document.documentElement, ['dunebookexampleAppModule']);

Note: The difference here is the use of upgradeAdapter.bootstrap instead of angular.bootstrap.

Making Angular 1.x service available to Angular 2.0

UpgradeAdapter also helps us make an Angular 1.x service available to Angular 2.0.

In this example we wish to use the old Angular routing module’s to get route parameters, therefore we need the $routeParams service.

upgradeProvider.upgradeNg1Provider('$routeParams');

And vise versa:

 angular.module('dunebookexampleApp').controller('dunebookexampleAppController',
   upgradeAdapter.downgradeNg2Provider(YourProviderType));

Now your service is almost set to work with Angular 1.x, but one thing you still need to do is add it to your provider’s list. Remember that unlike Angular 1.x, services in Angular 2.0 aren’t singleton, but an instance is created whenever they’re in the provider’s list. To create an instance of them available to Angular 1.x you need to use addProvider method.

Here’s an example for adding HTTP client of Angular 2.0 to Angular 1.x.

upgradeAdapter.addProvider(HTTP_PROVIDERS);

Now we can work with Angular 1.x and Angular 2.0 side by side. What has been left is to change the code from Angular 1.x to Angular 2.0.

Migrating a component

The Angular 1.5 component has a template (or template URL), controller and binding object. The method of migrating it to Angular 2.0 component is almost straight forward:

  1. The template stays the same and is moved into the template member of the ViewMetaData object being sent to the Component decorator. The data binding, of course, is changed to the Angular 2.0 syntax.
  2. The controller object is the class being exported. We need to replace the controller function to class (if haven’t done so already) and export it.
  3. All binding members are now component class members decorated with the Input decorator.

Migrating a directive

When dealing with an attribute directive, the migration process is a little different than the component, but not by far.

  1. The link method can be copied into the directive constructor.
  2. If you’re using $scope.$watch it is highly recommended that you switch to properties. You must do so in Angular 2.0, because there is no $scope.$watch there.
  3. Scope members are now class members decorated with @Input().
  4. The directive name is now on the selector member of the metadata object being sent to the Directive decorator. Please note that there is no difference between what is put in the decorator and the directive usage besides the square brackets for the attribute.

For the Angular 1.x component directive (the one used before Angular 1.5) the process is almost like the component process, but scope members relace the binding members.

Migrating a filter (to pipe)

  1. In filters, the function being returned needs to go to the pipe’s transform method, while the pipe class implements the PipeTransform interface. There are no changes in the arguments order.
  2. Decorate your class with the Pipe decoratior and give the filter name to the name member of the metadata object.

Migrating a service

The process of service migration is the easiest one, note that if you have migrated your service to be written in Typescript, all you need to do is to skip registering it, and have it in the providers array of your app’s main component.

  1. The service function becomes an exported class decorated with Injectable.
  2. All function members are class members.
  3. Register your service in the providers array of your app main component.
  4. Remove the angular.module(…).service(…) registration.

Although it is possible to write an Angular 2.0 application in ES5, ES6 and dart. Typescript is known to be the cleanest JavaScript transpiler there is. Moreover, you will see that Typescript is the most documented language in the angular.io site. Therefore, you may choose your favorite scripting language, because our application is built on Typescript.

Deven Rathore

Deven is an Entrepreneur, and Full-stack developer, Constantly learning and experiencing new things. He currently runs CodeSource.io and Dunebook.com.

Published by
Deven Rathore

Recent Posts

Free Applications and Websites to Enhance Coding Skills

Obtaining any skill means that one will continuously upgrade it to become professional. It’s impossible…

3 weeks ago

How to Use Disk Drill Partition Recovery Software for Mac

With the keyboard shortcut "Command(⌘) + Option(⌥) + Delete(⌫)" you can completely remove a file…

3 weeks ago

21 React Project Ideas for Beginners

For some weeks now, you have been putting in a lot of effort in understanding…

4 weeks ago

Reasons for Creating a Custom Transportation Management Software

Transportation management software is used by organizations to administer, control, and manage the transportation aspect…

1 month ago

21 Angular project ideas for beginners

Angular project ideas have become so handy in bringing evolution and slight changes to many…

2 months ago

Tips for Optimal SaaS Platform Development

According to BetterCloud, approximately 80 percent of mobile applications will be running on mobile software…

2 months ago