com.asayama.gwt.angular.site.examples.public.ServiceInjectionExampleDocumentation.html Maven / Gradle / Ivy
Among many things that Angular offers, dependency injection is perhaps one of
the more important features. In this example, we demonstrate how to inject
one service (provided by GWT Angular) into another service (a custom service).
By allowing Angular to manage the injection, the timing of instantiation of
the object is left up to the framework to manage. This means that these
service objects are not created until you actually request them (i.e. lazy
loading).
Custom Service
We define a custom service named MyService. This service depends on another
service, named HttpClient. By wrapping the HttpClient into our own service,
we can hide the complexity of data deserialization as well as error handling
in one place (i.e. MyService) so that the callers do not have to worry about
such details.
As you can see, in order to inject a service into another service, we merely
need to declare it as an instance member of the custom service class, and
annotate it with @Injector.Inject.
Service Registration in the Module
Once we have our service defined, we must not forget to register this in our
module, so that Angular knows to manage its life cycle.
You might be wondering why we need to register our custom service, MyService,
but not the HttpClient. This is because HttpClient is managed by another
module, com.asayama.gwt.angular.http.HTTP (see Configuration section below).
If you are injecting a custom service into another custom service, both of
which are defined in your own module, of course you have to register both of
them in your module's onModuleLoad() method. In this example, however, we are
injecting a service provided by GWT Angular (HttpClient) into a custom service
defined in this example module. We only need to register the latter.
Configuration
The following modules are required in the gwt.xml. Note that HttpClient
service is provided by and register in a module named
com.asayama.gwt.angular.http.HTTP, which you see in the inherits statement
below.
Controller and View
For reference, we show the controller and view components needed for this
example below. They do not directly play any roles in the injection of service
into another service (the point of this example), but they are provided here
for completeness.
The following Maven dependencies are required in the pom.xml.
<dependency>
<groupId>com.asayama.gwt</groupId>
<artifactId>gwt-angular-http</artifactId>
<version>{{ GWT_ANGULAR_VERSION }}</version>
</dependency>
You can also browse the full source code on Github.
{{ GITHUB_GWT_ANGULAR_EXAMPLES_URL }}/blob/master/gwt-angular-examples/ServiceInjection