Skip to content

Latest commit

 

History

History
56 lines (42 loc) · 1.62 KB

recipes__di.adoc

File metadata and controls

56 lines (42 loc) · 1.62 KB

Services and Dependency Injection

In this section, by a service we mean a program component that provides some specific functionality to other components. The most common examples of services are components working with REST APIs, internationalization, utility services, caches, etc.

There is a number of approaches of creating services and injecting them into your web components. We recommend to adopt the way described below.

Let’s imagine an application that shows notifications to users. These notifications are represented by a piece of text that is shown to users for a short time to inform them about some event. Different parts of the application need an ability to show notifications.

Here is a possible implementation:

index.html
<html>
<head>
	<link rel="import" href="src/recipes/di/forbidden-button.html">
	<script src="bower_components/webcomponentsjs/webcomponents-loader.js"></script>
</head>
<body>
    <forbidden-button></forbidden-button>
</body>
</html>
src/recipes/di/forbidden-button.html
link:../../../source/polymer-build/src/recipes/di/forbidden-button.html[role=include]
src/recipes/di/notification-service.html
link:../../../source/polymer-build/src/recipes/di/notification-service.html[role=include]

Result

So, basically we just instantiate some object, put it in a global variable and assign this variable to a component’s property.