Angular 1 and 2 Integration Typescript Example – Service

Similar to my last post, this is the Javascript + Typescript version of how services can be used in an Angular 1 and Angular 2 hybrid application. What I mean by Javascript + Typescript is, while your existing Angular 1 app is written in Javascript, you bring in Angular 2 components in Typescript. If you only want to use Javascript, see Angular 1 and 2 Integration Javascript Example -Service.

 

In this tutorial, we will be creating an example that demonstrates how Angular 1 service can be used by Angular 2 component in a hybrid application. You will also be able to see that the service is actually a single instance shared by the 2 worlds.

Folder

This is the folder structure. Source code is available here.

Angular 1 and 2 Integration Typescript Example - Service folder

user.service.js

The UserService  class is defined in this file. We will define it as service later in app.js. The reason why I am creating services in this way is that it supports inheritance and the code is more manageable, more importantly, In Angular 2, everything is typed, creating Angular 1 service in this way will make the upgrade much easier.

user.section.component.ts

This is the Angular 2 component that uses UserService . We inject the UserService  via constructor.

user.section.tpl.html

The template file of the Angular 2 component UserSection .

app.js

Compare to the Angular 1 and 2 Integration Javascript Example – Service, you will find that the app.js for this example is much simpler and it doesn’t even contain any code related to Angular 2. This is because we will create another separate file called boot.ts to handle the bootstrap and integration setup sort of things. Another good thing that we can benefit from this approach is that we may not even need to touch the existing app.js during the upgrade!

boot.ts

This is how we upgrade the Angular 1 service and bootstrap this hybrid application.

With the UpgradeAdapter, if you need to use Angular 2 Service in Angular 1, it is just as simple as below.

index.html

Finally, this is the index.html. In this example, both Angular 1 component and Angular 2 component have the same elements and they will share the same instance of UserService .

  • Set User – modify the instance variable user of UserService
  • Get User – display the instance variable user of UserService so you can see that the UserService is actually singleton
  • Get Users – a normal service methods that returns a list of users

Result

Below is a screenshot of this example.

Angular 1 and 2 Integration Typescript Example - Service result

Related Links


facebooktwittergoogle_plusredditlinkedin

Wayne Hong

Passionate Java full stack developer.