{ "id": "guide/upgrade", "title": "Upgrading from AngularJS to Angular", "contents": "\n\n\n
Angular is the name for the Angular of today and tomorrow.
\nAngularJS is the name for all 1.x versions of Angular.
AngularJS apps are great.\nAlways consider the business case before moving to Angular.\nAn important part of that case is the time and effort to get there.\nThis guide describes the built-in tools for efficiently migrating AngularJS projects over to the\nAngular platform, a piece at a time.
\nSome applications will be easier to upgrade than others, and there are\nmany ways to make it easier for yourself. It is possible to\nprepare and align AngularJS applications with Angular even before beginning\nthe upgrade process. These preparation steps are all about making the code\nmore decoupled, more maintainable, and better aligned with modern development\ntools. That means in addition to making the upgrade easier,\nyou will also improve the existing AngularJS applications.
\nOne of the keys to a successful upgrade is to do it incrementally,\nby running the two frameworks side by side in the same application, and\nporting AngularJS components to Angular one by one. This makes it possible\nto upgrade even large and complex applications without disrupting other\nbusiness, because the work can be done collaboratively and spread over\na period of time. The upgrade
module in Angular has been designed to\nmake incremental upgrading seamless.
There are many ways to structure AngularJS applications. When you begin\nto upgrade these applications to Angular, some will turn out to be\nmuch more easy to work with than others. There are a few key techniques\nand patterns that you can apply to future proof apps even before you\nbegin the migration.
\n\nThe AngularJS Style Guide\ncollects patterns and practices that have been proven to result in\ncleaner and more maintainable AngularJS applications. It contains a wealth\nof information about how to write and organize AngularJS code - and equally\nimportantly - how not to write and organize AngularJS code.
\nAngular is a reimagined version of the best parts of AngularJS. In that\nsense, its goals are the same as the AngularJS Style Guide's: To preserve\nthe good parts of AngularJS, and to avoid the bad parts. There's a lot\nmore to Angular than just that of course, but this does mean that\nfollowing the style guide helps make your AngularJS app more closely\naligned with Angular.
\nThere are a few rules in particular that will make it much easier to do\nan incremental upgrade using the Angular upgrade/static
module:
The Rule of 1\nstates that there should be one component per file. This not only makes\ncomponents easy to navigate and find, but will also allow us to migrate\nthem between languages and frameworks one at a time. In this example application,\neach controller, component, service, and filter is in its own source file.
\nThe Folders-by-Feature Structure\nand Modularity\nrules define similar principles on a higher level of abstraction: Different parts of the\napplication should reside in different directories and NgModules.
\nWhen an application is laid out feature per feature in this way, it can also be\nmigrated one feature at a time. For applications that don't already look like\nthis, applying the rules in the AngularJS style guide is a highly recommended\npreparation step. And this is not just for the sake of the upgrade - it is just\nsolid advice in general!
\nWhen you break application code down into one component per file, you often end\nup with a project structure with a large number of relatively small files. This is\na much neater way to organize things than a small number of large files, but it\ndoesn't work that well if you have to load all those files to the HTML page with\n<script> tags. Especially when you also have to maintain those tags in the correct\norder. That's why it's a good idea to start using a module loader.
\nUsing a module loader such as SystemJS,\nWebpack, or Browserify\nallows us to use the built-in module systems of TypeScript or ES2015.\nYou can use the import
and export
features that explicitly specify what code can\nand will be shared between different parts of the application. For ES5 applications\nyou can use CommonJS style require
and module.exports
features. In both cases,\nthe module loader will then take care of loading all the code the application needs\nin the correct order.
When moving applications into production, module loaders also make it easier\nto package them all up into production bundles with batteries included.
\nIf part of the Angular upgrade plan is to also take TypeScript into use, it makes\nsense to bring in the TypeScript compiler even before the upgrade itself begins.\nThis means there's one less thing to learn and think about during the actual upgrade.\nIt also means you can start using TypeScript features in your AngularJS code.
\nSince TypeScript is a superset of ECMAScript 2015, which in turn is a superset\nof ECMAScript 5, \"switching\" to TypeScript doesn't necessarily require anything\nmore than installing the TypeScript compiler and renaming files from\n*.js
to *.ts
. But just doing that is not hugely useful or exciting, of course.\nAdditional steps like the following can give us much more bang for the buck:
For applications that use a module loader, TypeScript imports and exports\n(which are really ECMAScript 2015 imports and exports) can be used to organize\ncode into modules.
\nType annotations can be gradually added to existing functions and variables\nto pin down their types and get benefits like build-time error checking,\ngreat autocompletion support and inline documentation.
\nJavaScript features new to ES2015, like arrow functions, let
s and const
s,\ndefault function parameters, and destructuring assignments can also be gradually\nadded to make the code more expressive.
Services and controllers can be turned into classes. That way they'll be a step\ncloser to becoming Angular service and component classes, which will make\nlife easier after the upgrade.
\nIn Angular, components are the main primitive from which user interfaces\nare built. You define the different portions of the UI as components and\ncompose them into a full user experience.
\nYou can also do this in AngularJS, using component directives. These are\ndirectives that define their own templates, controllers, and input/output bindings -\nthe same things that Angular components define. Applications built with\ncomponent directives are much easier to migrate to Angular than applications\nbuilt with lower-level features like ng-controller
, ng-include
, and scope\ninheritance.
To be Angular compatible, an AngularJS component directive should configure\nthese attributes:
\nrestrict: 'E'
. Components are usually used as elements.scope: {}
- an isolate scope. In Angular, components are always isolated\nfrom their surroundings, and you should do this in AngularJS too.bindToController: {}
. Component inputs and outputs should be bound\nto the controller instead of using the $scope
.controller
and controllerAs
. Components have their own controllers.template
or templateUrl
. Components have their own templates.Component directives may also use the following attributes:
\ntransclude: true/{}
, if the component needs to transclude content from elsewhere.require
, if the component needs to communicate with some parent component's\ncontroller.Component directives should not use the following attributes:
\ncompile
. This will not be supported in Angular.replace: true
. Angular never replaces a component element with the\ncomponent template. This attribute is also deprecated in AngularJS.priority
and terminal
. While AngularJS components may use these,\nthey are not used in Angular and it is better not to write code\nthat relies on them.An AngularJS component directive that is fully aligned with the Angular\narchitecture may look something like this:
\nAngularJS 1.5 introduces the component API\nthat makes it easier to define component directives like these. It is a good idea to use\nthis API for component directives for several reasons:
\ncontrollerAs
.scope
and restrict
.The component directive example from above looks like this when expressed\nusing the component API:
\nController lifecycle hook methods $onInit()
, $onDestroy()
, and $onChanges()
\nare another convenient feature that AngularJS 1.5 introduces. They all have nearly\nexact equivalents in Angular, so organizing component lifecycle\nlogic around them will ease the eventual Angular upgrade process.
The ngUpgrade library in Angular is a very useful tool for upgrading\nanything but the smallest of applications. With it you can mix and match\nAngularJS and Angular components in the same application and have them interoperate\nseamlessly. That means you don't have to do the upgrade work all at once,\nsince there's a natural coexistence between the two frameworks during the\ntransition period.
\nOne of the primary tools provided by ngUpgrade is called the UpgradeModule
.\nThis is a module that contains utilities for bootstrapping and managing hybrid\napplications that support both Angular and AngularJS code.
When you use ngUpgrade, what you're really doing is running both AngularJS and\nAngular at the same time. All Angular code is running in the Angular\nframework, and AngularJS code in the AngularJS framework. Both of these are the\nactual, fully featured versions of the frameworks. There is no emulation going on,\nso you can expect to have all the features and natural behavior of both frameworks.
\nWhat happens on top of this is that components and services managed by one\nframework can interoperate with those from the other framework. This happens\nin three main areas: Dependency injection, the DOM, and change detection.
\nDependency injection is front and center in both AngularJS and\nAngular, but there are some key differences between the two\nframeworks in how it actually works.
\n\n AngularJS\n | \n\n Angular\n | \n
---|---|
\n Dependency injection tokens are always strings\n | \n\n Tokens can have different types.\nThey are often classes. They may also be strings. \n | \n
\n There is exactly one injector. Even in multi-module applications,\neverything is poured into one big namespace. \n | \n \n There is a tree hierarchy of injectors,\nwith a root injector and an additional injector for each component. \n | \n
Even accounting for these differences you can still have dependency injection\ninteroperability. upgrade/static
resolves the differences and makes\neverything work seamlessly:
You can make AngularJS services available for injection to Angular code\nby upgrading them. The same singleton instance of each service is shared\nbetween the frameworks. In Angular these services will always be in the\nroot injector and available to all components.
\nYou can also make Angular services available for injection to AngularJS code\nby downgrading them. Only services from the Angular root injector can\nbe downgraded. Again, the same singleton instances are shared between the frameworks.\nWhen you register a downgraded service, you must explicitly specify a string token that you want to\nuse in AngularJS.
\nIn the DOM of a hybrid ngUpgrade application are components and\ndirectives from both AngularJS and Angular. These components\ncommunicate with each other by using the input and output bindings\nof their respective frameworks, which ngUpgrade bridges together. They may also\ncommunicate through shared injected dependencies, as described above.
\nThe key thing to understand about a hybrid application is that every element in the DOM is owned by exactly one of the two frameworks.\nThe other framework ignores it. If an element is\nowned by AngularJS, Angular treats it as if it didn't exist,\nand vice versa.
\nSo normally a hybrid application begins life as an AngularJS application,\nand it is AngularJS that processes the root template, e.g. the index.html.\nAngular then steps into the picture when an Angular component is used somewhere\nin an AngularJS template. That component's template will then be managed\nby Angular, and it may contain any number of Angular components and\ndirectives.
\nBeyond that, you may interleave the two frameworks.\nYou always cross the boundary between the two frameworks by one of two\nways:
\nBy using a component from the other framework: An AngularJS template\nusing an Angular component, or an Angular template using an\nAngularJS component.
\nBy transcluding or projecting content from the other framework. ngUpgrade\nbridges the related concepts of AngularJS transclusion and Angular content\nprojection together.
\nWhenever you use a component that belongs to the other framework, a\nswitch between framework boundaries occurs. However, that switch only\nhappens to the elements in the template of that component. Consider a situation\nwhere you use an Angular component from AngularJS like this:
\nThe DOM element <a-component>
will remain to be an AngularJS managed\nelement, because it's defined in an AngularJS template. That also\nmeans you can apply additional AngularJS directives to it, but not\nAngular directives. It is only in the template of the <a-component>
\nwhere Angular steps in. This same rule also applies when you\nuse AngularJS component directives from Angular.
The scope.$apply()
is how AngularJS detects changes and updates data bindings.\nAfter every event that occurs, scope.$apply()
gets called. This is done either\nautomatically by the framework, or manually by you.
In Angular things are different. While change detection still\noccurs after every event, no one needs to call scope.$apply()
for\nthat to happen. This is because all Angular code runs inside something\ncalled the Angular zone. Angular always\nknows when the code finishes, so it also knows when it should kick off\nchange detection. The code itself doesn't have to call scope.$apply()
\nor anything like it.
In the case of hybrid applications, the UpgradeModule
bridges the\nAngularJS and Angular approaches. Here's what happens:
Everything that happens in the application runs inside the Angular zone.\nThis is true whether the event originated in AngularJS or Angular code.\nThe zone triggers Angular change detection after every event.
\nThe UpgradeModule
will invoke the AngularJS $rootScope.$apply()
after\nevery turn of the Angular zone. This also triggers AngularJS change\ndetection after every event.
In practice, you do not need to call $apply()
,\nregardless of whether it is in AngularJS or Angular. The\nUpgradeModule
does it for us. You can still call $apply()
so there\nis no need to remove such calls from existing code. Those calls just trigger\nadditional AngularJS change detection checks in a hybrid application.
When you downgrade an Angular component and then use it from AngularJS,\nthe component's inputs will be watched using AngularJS change detection.\nWhen those inputs change, the corresponding properties in the component\nare set. You can also hook into the changes by implementing the\nOnChanges interface in the component,\njust like you could if it hadn't been downgraded.
\nCorrespondingly, when you upgrade an AngularJS component and use it from Angular,\nall the bindings defined for the component directive's scope
(or bindToController
)\nwill be hooked into Angular change detection. They will be treated\nas regular Angular inputs. Their values will be written to the upgraded component's\nscope (or controller) when they change.
Both AngularJS and Angular have their own concept of modules\nto help organize an application into cohesive blocks of functionality.
\nTheir details are quite different in architecture and implementation.\nIn AngularJS, you add Angular assets to the angular.module
property.\nIn Angular, you create one or more classes adorned with an NgModule
decorator\nthat describes Angular assets in metadata. The differences blossom from there.
In a hybrid application you run both versions of Angular at the same time.\nThat means that you need at least one module each from both AngularJS and Angular.\nYou will import UpgradeModule
inside the NgModule, and then use it for\nbootstrapping the AngularJS module.
For more information, see NgModules.
\nTo bootstrap a hybrid application, you must bootstrap each of the Angular and\nAngularJS parts of the application. You must bootstrap the Angular bits first and\nthen ask the UpgradeModule
to bootstrap the AngularJS bits next.
In an AngularJS application you have a root AngularJS module, which will also\nbe used to bootstrap the AngularJS application.
\nPure AngularJS applications can be automatically bootstrapped by using an ng-app
\ndirective somewhere on the HTML page. But for hybrid applications, you manually bootstrap via the\nUpgradeModule
. Therefore, it is a good preliminary step to switch AngularJS applications to use the\nmanual JavaScript angular.bootstrap
\nmethod even before switching them to hybrid mode.
Say you have an ng-app
driven bootstrap such as this one:
You can remove the ng-app
and ng-strict-di
directives from the HTML\nand instead switch to calling angular.bootstrap
from JavaScript, which\nwill result in the same thing:
To begin converting your AngularJS application to a hybrid, you need to load the Angular framework.\nYou can see how this can be done with SystemJS by following the instructions in Setup for Upgrading to AngularJS for selectively copying code from the QuickStart github repository.
\nYou also need to install the @angular/upgrade
package via npm install @angular/upgrade --save
\nand add a mapping for the @angular/upgrade/static
package:
Next, create an app.module.ts
file and add the following NgModule
class:
This bare minimum NgModule
imports BrowserModule
, the module every Angular browser-based app must have.\nIt also imports UpgradeModule
from @angular/upgrade/static
, which exports providers that will be used\nfor upgrading and downgrading services and components.
In the constructor of the AppModule
, use dependency injection to get a hold of the UpgradeModule
instance,\nand use it to bootstrap the AngularJS app in the AppModule.ngDoBootstrap
method.\nThe upgrade.bootstrap
method takes the exact same arguments as angular.bootstrap:
Note that you do not add a bootstrap
declaration to the @NgModule
decorator, since\nAngularJS will own the root template of the application.
Now you can bootstrap AppModule
using the platformBrowserDynamic.bootstrapModule
method.
Congratulations! You're running a hybrid application! The\nexisting AngularJS code works as before and you're ready to start adding Angular code.
\nOnce you're running a hybrid app, you can start the gradual process of upgrading\ncode. One of the more common patterns for doing that is to use an Angular component\nin an AngularJS context. This could be a completely new component or one that was\npreviously AngularJS but has been rewritten for Angular.
\nSay you have a simple Angular component that shows information about a hero:
\nIf you want to use this component from AngularJS, you need to downgrade it\nusing the downgradeComponent()
method. The result is an AngularJS\ndirective, which you can then register in the AngularJS module:
By default, Angular change detection will also run on the component for every\nAngularJS $digest
cycle. If you wish to only have change detection run when\nthe inputs change, you can set propagateDigest
to false
when calling\ndowngradeComponent()
.
Because HeroDetailComponent
is an Angular component, you must also add it to the\ndeclarations
in the AppModule
.
And because this component is being used from the AngularJS module, and is an entry point into\nthe Angular application, you must add it to the entryComponents
for the\nNgModule.
All Angular components, directives and pipes must be declared in an NgModule.
\nThe net result is an AngularJS directive called heroDetail
, that you can\nuse like any other directive in AngularJS templates.
Note that this AngularJS is an element directive (restrict: 'E'
) called heroDetail
.\nAn AngularJS element directive is matched based on its name.\nThe selector
metadata of the downgraded Angular component is ignored.
Most components are not quite this simple, of course. Many of them\nhave inputs and outputs that connect them to the outside world. An\nAngular hero detail component with inputs and outputs might look\nlike this:
\nThese inputs and outputs can be supplied from the AngularJS template, and the\ndowngradeComponent()
method takes care of wiring them up:
Note that even though you are in an AngularJS template, you're using Angular\nattribute syntax to bind the inputs and outputs. This is a requirement for downgraded\ncomponents. The expressions themselves are still regular AngularJS expressions.
\nThere's one notable exception to the rule of using Angular attribute syntax\nfor downgraded components. It has to do with input or output names that consist\nof multiple words. In Angular, you would bind these attributes using camelCase:
\nBut when using them from AngularJS templates, you must use kebab-case:
\nThe $event
variable can be used in outputs to gain access to the\nobject that was emitted. In this case it will be the Hero
object, because\nthat is what was passed to this.deleted.emit()
.
Since this is an AngularJS template, you can still use other AngularJS\ndirectives on the element, even though it has Angular binding attributes on it.\nFor example, you can easily make multiple copies of the component using ng-repeat
:
So, you can write an Angular component and then use it from AngularJS\ncode. This is useful when you start to migrate from lower-level\ncomponents and work your way up. But in some cases it is more convenient\nto do things in the opposite order: To start with higher-level components\nand work your way down. This too can be done using the upgrade/static
.\nYou can upgrade AngularJS component directives and then use them from\nAngular.
Not all kinds of AngularJS directives can be upgraded. The directive\nreally has to be a component directive, with the characteristics\ndescribed in the preparation guide above.\nThe safest bet for ensuring compatibility is using the\ncomponent API\nintroduced in AngularJS 1.5.
\nA simple example of an upgradable component is one that just has a template\nand a controller:
\nYou can upgrade this component to Angular using the UpgradeComponent
class.\nBy creating a new Angular directive that extends UpgradeComponent
and doing a super
call\ninside its constructor, you have a fully upgraded AngularJS component to be used inside Angular.\nAll that is left is to add it to AppModule
's declarations
array.
Upgraded components are Angular directives, instead of components, because Angular\nis unaware that AngularJS will create elements under it. As far as Angular knows, the upgraded\ncomponent is just a directive - a tag - and Angular doesn't have to concern itself with\nits children.
\nAn upgraded component may also have inputs and outputs, as defined by\nthe scope/controller bindings of the original AngularJS component\ndirective. When you use the component from an Angular template,\nprovide the inputs and outputs using Angular template syntax,\nobserving the following rules:
\n\n | \n\n Binding definition\n | \n\n Template syntax\n | \n
---|---|---|
\n Attribute binding\n | \n\n | \n \n | \n
\n Expression binding\n | \n\n | \n \n | \n
\n One-way binding\n | \n\n | \n \n | \n
\n Two-way binding\n | \n\n | \n \n As a two-way binding: | \n
For example, imagine a hero detail AngularJS component directive\nwith one input and one output:
\nYou can upgrade this component to Angular, annotate inputs and outputs in the upgrade directive,\nand then provide the input and output using Angular template syntax:
\nWhen you are using a downgraded Angular component from an AngularJS\ntemplate, the need may arise to transclude some content into it. This\nis also possible. While there is no such thing as transclusion in Angular,\nthere is a very similar concept called content projection. upgrade/static
\nis able to make these two features interoperate.
Angular components that support content projection make use of an <ng-content>
\ntag within them. Here's an example of such a component:
When using the component from AngularJS, you can supply contents for it. Just\nlike they would be transcluded in AngularJS, they get projected to the location\nof the <ng-content>
tag in Angular:
When AngularJS content gets projected inside an Angular component, it still\nremains in \"AngularJS land\" and is managed by the AngularJS framework.
\nJust as you can project AngularJS content into Angular components,\nyou can transclude Angular content into AngularJS components, whenever\nyou are using upgraded versions from them.
\nWhen an AngularJS component directive supports transclusion, it may use\nthe ng-transclude
directive in its template to mark the transclusion\npoint:
If you upgrade this component and use it from Angular, you can populate\nthe component tag with contents that will then get transcluded:
\nWhen running a hybrid app, you may encounter situations where you need to inject\nsome AngularJS dependencies into your Angular code.\nMaybe you have some business logic still in AngularJS services.\nMaybe you want access to AngularJS's built-in services like $location
or $timeout
.
In these situations, it is possible to upgrade an AngularJS provider to\nAngular. This makes it possible to then inject it somewhere in Angular\ncode. For example, you might have a service called HeroesService
in AngularJS:
You can upgrade the service using a Angular factory provider\nthat requests the service from the AngularJS $injector
.
Many developers prefer to declare the factory provider in a separate ajs-upgraded-providers.ts
file\nso that they are all together, making it easier to reference them, create new ones and\ndelete them once the upgrade is over.
It's also recommended to export the heroesServiceFactory
function so that Ahead-of-Time\ncompilation can pick it up.
Note: The 'heroes' string inside the factory refers to the AngularJS HeroesService
.\nIt is common in AngularJS apps to choose a service name for the token, for example \"heroes\",\nand append the \"Service\" suffix to create the class name.
You can then provide the service to Angular by adding it to the @NgModule
:
Then use the service inside your component by injecting it in the component constructor using its class as a type annotation:
\nIn this example you upgraded a service class.\nYou can use a TypeScript type annotation when you inject it. While it doesn't\naffect how the dependency is handled, it enables the benefits of static type\nchecking. This is not required though, and any AngularJS service, factory, or\nprovider can be upgraded.
\nIn addition to upgrading AngularJS dependencies, you can also downgrade\nAngular dependencies, so that you can use them from AngularJS. This can be\nuseful when you start migrating services to Angular or creating new services\nin Angular while retaining components written in AngularJS.
\nFor example, you might have an Angular service called Heroes
:
Again, as with Angular components, register the provider with the NgModule
by adding it to the module's providers
list.
Now wrap the Angular Heroes
in an AngularJS factory function using downgradeInjectable()
\nand plug the factory into an AngularJS module.\nThe name of the AngularJS dependency is up to you:
After this, the service is injectable anywhere in AngularJS code:
\nWhen building applications, you want to ensure that only the required resources are loaded when necessary. Whether that be loading of assets or code, making sure everything that can be deferred until needed keeps your application running efficiently. This is especially true when running different frameworks in the same application.
\nLazy loading is a technique that defers the loading of required assets and code resources until they are actually used. This reduces startup time and increases efficiency, especially when running different frameworks in the same application.
\nWhen migrating large applications from AngularJS to Angular using a hybrid approach, you want to migrate some of the most commonly used features first, and only use the less commonly used features if needed. Doing so helps you ensure that the application is still providing a seamless experience for your users while you are migrating.
\nIn most environments where both Angular and AngularJS are used to render the application, both frameworks are loaded in the initial bundle being sent to the client. This results in both increased bundle size and possible reduced performance.
\nOverall application performance is affected in cases where the user stays on Angular-rendered pages because the AngularJS framework and application are still loaded and running, even if they are never accessed.
\nYou can take steps to mitigate both bundle size and performance issues. By isolating your AngularJS app to a separate bundle, you can take advantage of lazy loading to load, bootstrap, and render the AngularJS application only when needed. This strategy reduces your initial bundle size, defers any potential impact from loading both frameworks until absolutely necessary, and keeps your application running as efficiently as possible.
\nThe steps below show you how to do the following:
\nmatcher
function for AngularJS-specific URLs and configure the Angular Router
with the custom matcher for AngularJS routes.As of Angular version 8, lazy loading code can be accomplished simply by using the dynamic import syntax import('...')
. In your application, you create a new service that uses dynamic imports to lazy load AngularJS.
The service uses the import()
method to load your bundled AngularJS application lazily. This decreases the initial bundle size of your application as you're not loading code your user doesn't need yet. You also need to provide a way to bootstrap the application manually after it has been loaded. AngularJS provides a way to manually bootstrap an application using the angular.bootstrap() method with a provided HTML element. Your AngularJS app should also expose a bootstrap
method that bootstraps the AngularJS app.
To ensure any necessary teardown is triggered in the AngularJS app, such as removal of global listeners, you also implement a method to call the $rootScope.destroy()
method.
Your AngularJS application is configured with only the routes it needs to render content. The remaining routes in your application are handled by the Angular Router. The exposed bootstrap
method is called in your Angular app to bootstrap the AngularJS application after the bundle is loaded.
Note: After AngularJS is loaded and bootstrapped, listeners such as those wired up in your route configuration will continue to listen for route changes. To ensure listeners are shut down when AngularJS isn't being displayed, configure an otherwise
option with the $routeProvider that renders an empty template. This assumes all other routes will be handled by Angular.
In your Angular application, you need a component as a placeholder for your AngularJS content. This component uses the service you create to load and bootstrap your AngularJS app after the component is initialized.
\nWhen the Angular Router matches a route that uses AngularJS, the AngularJSComponent
is rendered, and the content is rendered within the AngularJS ng-view
directive. When the user navigates away from the route, the $rootScope
is destroyed on the AngularJS application.
To configure the Angular Router, you must define a route for AngularJS URLs. To match those URLs, you add a route configuration that uses the matcher
property. The matcher
allows you to use custom pattern matching for URL paths. The Angular Router tries to match on more specific routes such as static and variable routes first. When it doesn't find a match, it then looks at custom matchers defined in your route configuration. If the custom matchers don't match a route, it then goes to catch-all routes, such as a 404 page.
The following example defines a custom matcher function for AngularJS routes.
\nThe following code adds a route object to your routing configuration using the matcher
property and custom matcher, and the component
property with AngularJSComponent
.
When your application matches a route that needs AngularJS, the AngularJS app is loaded and bootstrapped, the AngularJS routes match the necessary URL to render their content, and your application continues to run with both AngularJS and Angular frameworks.
\nIn AngularJS, the $location service handles all routing configuration and navigation, encoding and decoding of URLS, redirects, and interactions with browser APIs. Angular uses its own underlying Location
service for all of these tasks.
When you migrate from AngularJS to Angular you will want to move as much responsibility as possible to Angular, so that you can take advantage of new APIs. To help with the transition, Angular provides the LocationUpgradeModule
. This module enables a unified location service that shifts responsibilities from the AngularJS $location
service to the Angular Location
service.
To use the LocationUpgradeModule
, import the symbol from @angular/common/upgrade
and add it to your AppModule
imports using the static LocationUpgradeModule.config()
method.
The LocationUpgradeModule.config()
method accepts a configuration object that allows you to configure options including the LocationStrategy
with the useHash
property, and the URL prefix with the hashPrefix
property.
The useHash
property defaults to false
, and the hashPrefix
defaults to an empty string
. Pass the configuration object to override the defaults.
Note: See the LocationUpgradeConfig
for more configuration options available to the LocationUpgradeModule.config()
method.
This registers a drop-in replacement for the $location
provider in AngularJS. Once registered, all navigation, routing broadcast messages, and any necessary digest cycles in AngularJS triggered during navigation are handled by Angular. This gives you a single way to navigate within both sides of your hybrid application consistently.
For usage of the $location
service as a provider in AngularJS, you need to downgrade the $locationShim
using a factory provider.
Once you introduce the Angular Router, using the Angular Router triggers navigations through the unified location service, still providing a single source for navigating with AngularJS and Angular.
\n\nIn this section, you'll learn to prepare and upgrade an application with ngUpgrade
.\nThe example app is Angular PhoneCat\nfrom the original AngularJS tutorial,\nwhich is where many of us began our Angular adventures. Now you'll see how to\nbring that application to the brave new world of Angular.
During the process you'll learn how to apply the steps outlined in the\npreparation guide. You'll align the application\nwith Angular and also start writing in TypeScript.
\nTo follow along with the tutorial, clone the\nangular-phonecat repository\nand apply the steps as you go.
\nIn terms of project structure, this is where the work begins:
\nThis is actually a pretty good starting point. The code uses the AngularJS 1.5\ncomponent API and the organization follows the\nAngularJS Style Guide,\nwhich is an important preparation step before\na successful upgrade.
\nEach component, service, and filter is in its own source file, as per the\nRule of 1.
\nThe core
, phone-detail
, and phone-list
modules are each in their\nown subdirectory. Those subdirectories contain the JavaScript code as well as\nthe HTML templates that go with each particular feature. This is in line with the\nFolders-by-Feature Structure\nand Modularity\nrules.
Unit tests are located side-by-side with application code where they are easily\nfound, as described in the rules for\nOrganizing Tests.
\nSince you're going to be writing Angular code in TypeScript, it makes sense to\nbring in the TypeScript compiler even before you begin upgrading.
\nYou'll also start to gradually phase out the Bower package manager in favor\nof NPM, installing all new dependencies using NPM, and eventually removing Bower from the project.
\nBegin by installing TypeScript to the project.
\nInstall type definitions for the existing libraries that\nyou're using but that don't come with prepackaged types: AngularJS, AngularJS Material, and the\nJasmine unit test framework.
\nFor the PhoneCat app, we can install the necessary type definitions by running the following command:
\nIf you are using AngularJS Material, you can install the type definitions via:
\nYou should also configure the TypeScript compiler with a tsconfig.json
in the project directory\nas described in the TypeScript Configuration guide.\nThe tsconfig.json
file tells the TypeScript compiler how to turn your TypeScript files\ninto ES5 code bundled into CommonJS modules.
Finally, you should add some npm scripts in package.json
to compile the TypeScript files to\nJavaScript (based on the tsconfig.json
configuration file):
Now launch the TypeScript compiler from the command line in watch mode:
\nKeep this process running in the background, watching and recompiling as you make changes.
\nNext, convert your current JavaScript files into TypeScript. Since\nTypeScript is a super-set of ECMAScript 2015, which in turn is a super-set\nof ECMAScript 5, you can simply switch the file extensions from .js
to .ts
\nand everything will work just like it did before. As the TypeScript compiler\nruns, it emits the corresponding .js
file for every .ts
file and the\ncompiled JavaScript is what actually gets executed. If you start\nthe project HTTP server with npm start
, you should see the fully functional\napplication in your browser.
Now that you have TypeScript though, you can start benefiting from some of its\nfeatures. There's a lot of value the language can provide to AngularJS applications.
\nFor one thing, TypeScript is a superset of ES2015. Any app that has previously\nbeen written in ES5 - like the PhoneCat example has - can with TypeScript\nstart incorporating all of the JavaScript features that are new to ES2015.\nThese include things like let
s and const
s, arrow functions, default function\nparameters, and destructuring assignments.
Another thing you can do is start adding type safety to your code. This has\nactually partially already happened because of the AngularJS typings you installed.\nTypeScript are checking that you are calling AngularJS APIs correctly when you do\nthings like register components to Angular modules.
\nBut you can also start adding type annotations to get even more\nout of TypeScript's type system. For instance, you can annotate the checkmark\nfilter so that it explicitly expects booleans as arguments. This makes it clearer\nwhat the filter is supposed to do.
\nIn the Phone
service, you can explicitly annotate the $resource
service dependency\nas an angular.resource.IResourceService
- a type defined by the AngularJS typings.
You can apply the same trick to the application's route configuration file in app.config.ts
,\nwhere you are using the location and route services. By annotating them accordingly TypeScript\ncan verify you're calling their APIs with the correct kinds of arguments.
The AngularJS 1.x type definitions\nyou installed are not officially maintained by the Angular team,\nbut are quite comprehensive. It is possible to make an AngularJS 1.x application\nfully type-annotated with the help of these definitions.
\nIf this is something you wanted to do, it would be a good idea to enable\nthe noImplicitAny
configuration option in tsconfig.json
. This would\ncause the TypeScript compiler to display a warning when there's any code that\ndoes not yet have type annotations. You could use it as a guide to inform\nus about how close you are to having a fully annotated project.
Another TypeScript feature you can make use of is classes. In particular, you\ncan turn component controllers into classes. That way they'll be a step\ncloser to becoming Angular component classes, which will make life\neasier once you upgrade.
\nAngularJS expects controllers to be constructor functions. That's exactly what\nES2015/TypeScript classes are under the hood, so that means you can just plug in a\nclass as a component controller and AngularJS will happily use it.
\nHere's what the new class for the phone list component controller looks like:
\nWhat was previously done in the controller function is now done in the class\nconstructor function. The dependency injection annotations are attached\nto the class using a static property $inject
. At runtime this becomes the\nPhoneListController.$inject
property.
The class additionally declares three members: The array of phones, the name of\nthe current sort key, and the search query. These are all things you have already\nbeen attaching to the controller but that weren't explicitly declared anywhere.\nThe last one of these isn't actually used in the TypeScript code since it's only\nreferred to in the template, but for the sake of clarity you should define all of the\ncontroller members.
\nIn the Phone detail controller, you'll have two members: One for the phone\nthat the user is looking at and another for the URL of the currently displayed image:
\nThis makes the controller code look a lot more like Angular already. You're\nall set to actually introduce Angular into the project.
\nIf you had any AngularJS services in the project, those would also be\na good candidate for converting to classes, since like controllers,\nthey're also constructor functions. But you only have the Phone
factory\nin this project, and that's a bit special since it's an ngResource
\nfactory. So you won't be doing anything to it in the preparation stage.\nYou'll instead turn it directly into an Angular service.
Having completed the preparation work, get going with the Angular\nupgrade of PhoneCat. You'll do this incrementally with the help of\nngUpgrade that comes with Angular.\nBy the time you're done, you'll be able to remove AngularJS from the project\ncompletely, but the key is to do this piece by piece without breaking the application.
\nThe project also contains some animations.\nYou won't upgrade them in this version of the guide.\nTurn to the Angular animations guide to learn about that.
\nInstall Angular into the project, along with the SystemJS module loader.\nTake a look at the results of the upgrade setup instructions\nand get the following configurations from there:
\npackage.json
systemjs.config.js
to the project root directory.Once these are done, run:
\nSoon you can load Angular dependencies into the application via index.html
,\nbut first you need to do some directory path adjustments.\nYou'll need to load files from node_modules
and the project root instead of\nfrom the /app
directory as you've been doing to this point.
Move the app/index.html
file to the project root directory. Then change the\ndevelopment server root path in package.json
to also point to the project root\ninstead of app
:
Now you're able to serve everything from the project root to the web browser. But you do not\nwant to have to change all the image and data paths used in the application code to match\nthe development setup. For that reason, you'll add a <base>
tag to index.html
, which will\ncause relative URLs to be resolved back to the /app
directory:
Now you can load Angular via SystemJS. You'll add the Angular polyfills and the\nSystemJS config to the end of the <head>
section, and then you'll use System.import
\nto load the actual application:
You also need to make a couple of adjustments\nto the systemjs.config.js
file installed during upgrade setup.
Point the browser to the project root when loading things through SystemJS,\ninstead of using the <base>
URL.
Install the upgrade
package via npm install @angular/upgrade --save
\nand add a mapping for the @angular/upgrade/static
package.
Now create the root NgModule
class called AppModule
.\nThere is already a file named app.module.ts
that holds the AngularJS module.\nRename it to app.module.ajs.ts
and update the corresponding script name in the index.html
as well.\nThe file contents remain:
Now create a new app.module.ts
with the minimum NgModule
class:
Next, you'll bootstrap the application as a hybrid application\nthat supports both AngularJS and Angular components. After that,\nyou can start converting the individual pieces to Angular.
\nThe application is currently bootstrapped using the AngularJS ng-app
directive\nattached to the <html>
element of the host page. This will no longer work in the hybrid\napp. Switch to the ngUpgrade bootstrap method\ninstead.
First, remove the ng-app
attribute from index.html
.\nThen import UpgradeModule
in the AppModule
, and override its ngDoBootstrap
method:
Note that you are bootstrapping the AngularJS module from inside ngDoBootstrap
.\nThe arguments are the same as you would pass to angular.bootstrap
if you were manually\nbootstrapping AngularJS: the root element of the application; and an array of the\nAngularJS 1.x modules that you want to load.
Finally, bootstrap the AppModule
in app/main.ts
.\nThis file has been configured as the application entrypoint in systemjs.config.js
,\nso it is already being loaded by the browser.
Now you're running both AngularJS and Angular at the same time. That's pretty\nexciting! You're not running any actual Angular components yet. That's next.
\n@types/angular
is declared as a UMD module, and due to the way\nUMD typings\nwork, once you have an ES6 import
statement in a file all UMD typed modules must also be\nimported via import
statements instead of being globally available.
AngularJS is currently loaded by a script tag in index.html
, which means that the whole app\nhas access to it as a global and uses the same instance of the angular
variable.\nIf you used import * as angular from 'angular'
instead, you'd also have to\nload every file in the AngularJS app to use ES2015 modules in order to ensure AngularJS was being\nloaded correctly.
This is a considerable effort and it often isn't worth it, especially since you are in the\nprocess of moving your code to Angular.\nInstead, declare angular
as angular.IAngularStatic
to indicate it is a global variable\nand still have full typing support.
The first piece you'll port over to Angular is the Phone
service, which\nresides in app/core/phone/phone.service.ts
and makes it possible for components\nto load phone information from the server. Right now it's implemented with\nngResource and you're using it for two things:
You can replace this implementation with an Angular service class, while\nkeeping the controllers in AngularJS land.
\nIn the new version, you import the Angular HTTP module and call its HttpClient
service instead of ngResource
.
Re-open the app.module.ts
file, import and add HttpClientModule
to the imports
array of the AppModule
:
Now you're ready to upgrade the Phone service itself. Replace the ngResource-based\nservice in phone.service.ts
with a TypeScript class decorated as @Injectable
:
The @Injectable
decorator will attach some dependency injection metadata\nto the class, letting Angular know about its dependencies. As described\nby the Dependency Injection Guide,\nthis is a marker decorator you need to use for classes that have no other\nAngular decorators but still need to have their dependencies injected.
In its constructor the class expects to get the HttpClient
service. It will\nbe injected to it and it is stored as a private field. The service is then\nused in the two instance methods, one of which loads the list of all phones,\nand the other loads the details of a specified phone:
The methods now return observables of type PhoneData
and PhoneData[]
. This is\na type you don't have yet. Add a simple interface for it:
@angular/upgrade/static
has a downgradeInjectable
method for the purpose of making\nAngular services available to AngularJS code. Use it to plug in the Phone
service:
Here's the full, final code for the service:
\nNotice that you're importing the map
operator of the RxJS Observable
separately.\nDo this for every RxJS operator.
The new Phone
service has the same features as the original, ngResource
-based service.\nBecause it's an Angular service, you register it with the NgModule
providers:
Now that you are loading phone.service.ts
through an import that is resolved\nby SystemJS, you should remove the <script> tag for the service from index.html
.\nThis is something you'll do to all components as you upgrade them. Simultaneously\nwith the AngularJS to Angular upgrade you're also migrating code from scripts to modules.
At this point, you can switch the two components to use the new service\ninstead of the old one. While you $inject
it as the downgraded phone
factory,\nit's really an instance of the Phone
class and you annotate its type accordingly:
Now there are two AngularJS components using an Angular service!\nThe components don't need to be aware of this, though the fact that the\nservice returns observables and not promises is a bit of a giveaway.\nIn any case, what you've achieved is a migration of a service to Angular\nwithout having to yet migrate the components that use it.
\nYou could use the toPromise
method of Observable
to turn those\nobservables into promises in the service. In many cases that reduce\nthe number of changes to the component controllers.
Upgrade the AngularJS components to Angular components next.\nDo it one component at a time while still keeping the application in hybrid mode.\nAs you make these conversions, you'll also define your first Angular pipes.
\nLook at the phone list component first. Right now it contains a TypeScript\ncontroller class and a component definition object. You can morph this into\nan Angular component by just renaming the controller class and turning the\nAngularJS component definition object into an Angular @Component
decorator.\nYou can then also remove the static $inject
property from the class:
The selector
attribute is a CSS selector that defines where on the page the component\nshould go. In AngularJS you do matching based on component names, but in Angular you\nhave these explicit selectors. This one will match elements with the name phone-list
,\njust like the AngularJS version did.
Now convert the template of this component into Angular syntax.\nThe search controls replace the AngularJS $ctrl
expressions\nwith Angular's two-way [(ngModel)]
binding syntax:
Replace the list's ng-repeat
with an *ngFor
as\ndescribed in the Template Syntax page.\nReplace the image tag's ng-src
with a binding to the native src
property.
The built-in AngularJS filter
and orderBy
filters do not exist in Angular,\nso you need to do the filtering and sorting yourself.
You replaced the filter
and orderBy
filters with bindings to the getPhones()
controller method,\nwhich implements the filtering and ordering logic inside the component itself.
Now you need to downgrade the Angular component so you can use it in AngularJS.\nInstead of registering a component, you register a phoneList
directive,\na downgraded version of the Angular component.
The as angular.IDirectiveFactory
cast tells the TypeScript compiler\nthat the return value of the downgradeComponent
method is a directive factory.
The new PhoneListComponent
uses the Angular ngModel
directive, located in the FormsModule
.\nAdd the FormsModule
to NgModule
imports, declare the new PhoneListComponent
and\nfinally add it to entryComponents
since you downgraded it:
Remove the <script> tag for the phone list component from index.html
.
Now set the remaining phone-detail.component.ts
as follows:
This is similar to the phone list component.\nThe new wrinkle is the RouteParams
type annotation that identifies the routeParams
dependency.
The AngularJS injector has an AngularJS router dependency called $routeParams
,\nwhich was injected into PhoneDetails
when it was still an AngularJS controller.\nYou intend to inject it into the new PhoneDetailsComponent
.
Unfortunately, AngularJS dependencies are not automatically available to Angular components.\nYou must upgrade this service via a factory provider\nto make $routeParams
an Angular injectable.\nDo that in a new file called ajs-upgraded-providers.ts
and import it in app.module.ts
:
Convert the phone detail component template into Angular syntax as follows:
\nThere are several notable changes here:
\nYou've removed the $ctrl.
prefix from all expressions.
You've replaced ng-src
with property\nbindings for the standard src
property.
You're using the property binding syntax around ng-class
. Though Angular\ndoes have a very similar ngClass
\nas AngularJS does, its value is not magically evaluated as an expression.\nIn Angular, you always specify in the template when an attribute's value is\na property expression, as opposed to a literal string.
You've replaced ng-repeat
s with *ngFor
s.
You've replaced ng-click
with an event binding for the standard click
.
You've wrapped the whole template in an ngIf
that causes it only to be\nrendered when there is a phone present. You need this because when the component\nfirst loads, you don't have phone
yet and the expressions will refer to a\nnon-existing value. Unlike in AngularJS, Angular expressions do not fail silently\nwhen you try to refer to properties on undefined objects. You need to be explicit\nabout cases where this is expected.
Add PhoneDetailComponent
component to the NgModule
declarations and entryComponents:
You should now also remove the phone detail component <script> tag from index.html
.
The AngularJS directive had a checkmark
filter.\nTurn that into an Angular pipe.
There is no upgrade method to convert filters into pipes.\nYou won't miss it.\nIt's easy to turn the filter function into an equivalent Pipe class.\nThe implementation is the same as before, repackaged in the transform
method.\nRename the file to checkmark.pipe.ts
to conform with Angular conventions:
Now import and declare the newly created pipe and\nremove the filter <script> tag from index.html
:
To use AOT with a hybrid app, you have to first set it up like any other Angular application,\nas shown in the Ahead-of-time Compilation chapter.
\nThen change main-aot.ts
to bootstrap the AppComponentFactory
that was generated\nby the AOT compiler:
You need to load all the AngularJS files you already use in index.html
in aot/index.html
\nas well:
These files need to be copied together with the polyfills. The files the application\nneeds at runtime, like the .json
phone lists and images, also need to be copied.
Install fs-extra
via npm install fs-extra --save-dev
for better file copying, and change\ncopy-dist-files.js
to the following:
And that's all you need to use AOT while upgrading your app!
\nAt this point, you've replaced all AngularJS application components with\ntheir Angular counterparts, even though you're still serving them from the AngularJS router.
\nAngular has an all-new router.
\nLike all routers, it needs a place in the UI to display routed views.\nFor Angular that's the <router-outlet>
and it belongs in a root component\nat the top of the applications component tree.
You don't yet have such a root component, because the app is still managed as an AngularJS app.\nCreate a new app.component.ts
file with the following AppComponent
class:
It has a simple template that only includes the <router-outlet>
.\nThis component just renders the contents of the active route and nothing else.
The selector tells Angular to plug this root component into the <phonecat-app>
\nelement on the host web page when the application launches.
Add this <phonecat-app>
element to the index.html
.\nIt replaces the old AngularJS ng-view
directive:
A router needs configuration whether it's the AngularJS or Angular or any other router.
\nThe details of Angular router configuration are best left to the Routing documentation\nwhich recommends that you create a NgModule
dedicated to router configuration\n(called a Routing Module).
This module defines a routes
object with two routes to the two phone components\nand a default route for the empty path.\nIt passes the routes
to the RouterModule.forRoot
method which does the rest.
A couple of extra providers enable routing with \"hash\" URLs such as #!/phones
\ninstead of the default \"push state\" strategy.
Now update the AppModule
to import this AppRoutingModule
and also the\ndeclare the root AppComponent
as the bootstrap component.\nThat tells Angular that it should bootstrap the app with the root AppComponent
and\ninsert its view into the host web page.
You must also remove the bootstrap of the AngularJS module from ngDoBootstrap()
in app.module.ts
\nand the UpgradeModule
import.
And since you are routing to PhoneListComponent
and PhoneDetailComponent
directly rather than\nusing a route template with a <phone-list>
or <phone-detail>
tag, you can do away with their\nAngular selectors as well.
You no longer have to hardcode the links to phone details in the phone list.\nYou can generate data bindings for each phone's id
to the routerLink
directive\nand let that directive construct the appropriate URL to the PhoneDetailComponent
:
See the Routing page for details.
\nThe Angular router passes route parameters differently.\nCorrect the PhoneDetail
component constructor to expect an injected ActivatedRoute
object.\nExtract the phoneId
from the ActivatedRoute.snapshot.params
and fetch the phone data as before:
You are now running a pure Angular application!
\nIt is time to take off the training wheels and let the application begin\nits new life as a pure, shiny Angular app. The remaining tasks all have to\ndo with removing code - which of course is every programmer's favorite task!
\nThe application is still bootstrapped as a hybrid app.\nThere's no need for that anymore.
\nSwitch the bootstrap method of the application from the UpgradeModule
to the Angular way.
If you haven't already, remove all references to the UpgradeModule
from app.module.ts
,\nas well as any factory provider\nfor AngularJS services, and the app/ajs-upgraded-providers.ts
file.
Also remove any downgradeInjectable()
or downgradeComponent()
you find,\ntogether with the associated AngularJS factory or directive declarations.\nSince you no longer have downgraded components, you no longer list them\nin entryComponents
.
You may also completely remove the following files. They are AngularJS\nmodule configuration files and not needed in Angular:
\napp/app.module.ajs.ts
app/app.config.ts
app/core/core.module.ts
app/core/phone/phone.module.ts
app/phone-detail/phone-detail.module.ts
app/phone-list/phone-list.module.ts
The external typings for AngularJS may be uninstalled as well. The only ones\nyou still need are for Jasmine and Angular polyfills.\nThe @angular/upgrade
package and its mapping in systemjs.config.js
can also go.
Finally, from index.html
, remove all references to AngularJS scripts and jQuery.\nWhen you're done, this is what it should look like:
That is the last you'll see of AngularJS! It has served us well but now\nit's time to say goodbye.
\nTests can not only be retained through an upgrade process, but they can also be\nused as a valuable safety measure when ensuring that the application does not\nbreak during the upgrade. E2E tests are especially useful for this purpose.
\nThe PhoneCat project has both E2E Protractor tests and some Karma unit tests in it.\nOf these two, E2E tests can be dealt with much more easily: By definition,\nE2E tests access the application from the outside by interacting with\nthe various UI elements the app puts on the screen. E2E tests aren't really that\nconcerned with the internal structure of the application components. That\nalso means that, although you modify the project quite a bit during the upgrade, the E2E\ntest suite should keep passing with just minor modifications. You\ndidn't change how the application behaves from the user's point of view.
\nDuring TypeScript conversion, there is nothing to do to keep E2E tests\nworking. But when you change the bootstrap to that of a Hybrid app,\nyou must make a few changes.
\nUpdate the protractor-conf.js
to sync with hybrid apps:
When you start to upgrade components and their templates to Angular, you'll make more changes\nbecause the E2E tests have matchers that are specific to AngularJS.\nFor PhoneCat you need to make the following changes in order to make things work with Angular:
\n\n Previous code\n | \n\n New code\n | \n\n Notes\n | \n
---|---|---|
\n | \n \n | \n \n The repeater matcher relies on AngularJS | \n
\n | \n \n | \n \n The repeater matcher relies on AngularJS | \n
\n | \n \n | \n \n The model matcher relies on AngularJS | \n
\n | \n \n | \n \n The model matcher relies on AngularJS | \n
\n | \n \n | \n \n The binding matcher relies on AngularJS data binding \n | \n
When the bootstrap method is switched from that of UpgradeModule
to\npure Angular, AngularJS ceases to exist on the page completely.\nAt this point, you need to tell Protractor that it should not be looking for\nan AngularJS app anymore, but instead it should find Angular apps from\nthe page.
Replace the ng12Hybrid
previously added with the following in protractor-conf.js
:
Also, there are a couple of Protractor API calls in the PhoneCat test code that\nare using the AngularJS $location
service under the hood. As that\nservice is no longer present after the upgrade, replace those calls with ones\nthat use WebDriver's generic URL APIs instead. The first of these is\nthe redirection spec:
And the second is the phone links spec:
\nFor unit tests, on the other hand, more conversion work is needed. Effectively\nthey need to be upgraded along with the production code.
\nDuring TypeScript conversion no changes are strictly necessary. But it may be\na good idea to convert the unit test code into TypeScript as well.
\nFor instance, in the phone detail component spec, you can use ES2015\nfeatures like arrow functions and block-scoped variables and benefit from the type\ndefinitions of the AngularJS services you're consuming:
\nOnce you start the upgrade process and bring in SystemJS, configuration changes\nare needed for Karma. You need to let SystemJS load all the new Angular code,\nwhich can be done with the following kind of shim file:
\nThe shim first loads the SystemJS configuration, then Angular's test support libraries,\nand then the application's spec files themselves.
\nKarma configuration should then be changed so that it uses the application root dir\nas the base directory, instead of app
.
Once done, you can load SystemJS and other dependencies, and also switch the configuration\nfor loading application files so that they are not included to the page by Karma. You'll let\nthe shim and SystemJS load them.
\nSince the HTML templates of Angular components will be loaded as well, you must help\nKarma out a bit so that it can route them to the right paths:
\nThe unit test files themselves also need to be switched to Angular when their production\ncounterparts are switched. The specs for the checkmark pipe are probably the most straightforward,\nas the pipe has no dependencies:
\nThe unit test for the phone service is a bit more involved. You need to switch from the mocked-out\nAngularJS $httpBackend
to a mocked-out Angular Http backend.
For the component specs, you can mock out the Phone
service itself, and have it provide\ncanned phone data. You use Angular's component unit testing APIs for both components.
Finally, revisit both of the component tests when you switch to the Angular\nrouter. For the details component, provide a mock of Angular ActivatedRoute
object\ninstead of using the AngularJS $routeParams
.
And for the phone list component, a few adjustments to the router make\nthe RouteLink
directives work.