Angular 1 and 2 Integration Javascript Example – Service

In my last example, we have seen how angular 1 directives and Angular 2 components can be used together. Now, let’s see how we can use Angular 1 service within Angular 2 component, and this is mainly this post is about. I honestly don’t see any situation that Angular 2 services needed to be used by Angular 1 directives, but anyway, just in case, I will cover it as well at the end of the example. For Typescript version of this example, please see Angular 1 and 2 Integration Typescript 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 Javascript 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.js

This is the Angular 2 component that uses UserService . We inject the UserService  via constructor. But this is not all, we still needs setup in app.js.

user.section.tpl.html

The template file of the Angular 2 component UserSection .

app.js

Unlike my previous example, I instantiate the UpgradeAdapter here in app.js, simply because I want to keep the code short and I don’t need to use the adapter anywhere else in this example. As you can see from below code, We defined UserService  as Angular 1 service and we also called adapter.upgradeNg1Provider  to upgrade it so it can be used by Angular 2 components or services.

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 Javascript Example - Service result

Related Links


facebooktwittergoogle_plusredditlinkedin

Wayne Hong

Passionate Java full stack developer.