Web
Analytics
angular 4 services with example - Tutorial

For Consultation : +91 9887575540

Stay Connected :

When we write the angular source code we usually need some data functions that would be shared across different components in an application. In that condition, we have to write same function code in different components that don’t make sense. In this scenario, we can develop some angular services which may be shared across different components.we also capable to share data across different components using Angular services. Angular services are the concept of dependency injection.
Angular services are task-based. Services are reusable code which shared among different components. Angular provides built-in(HTTP, router, animation, form, UI Library,) and custom services. services work on dependency injection mechanism.
Services may be written by just defining a typescript(with extension .service.ts) class with decorator @Injectable annotation. Providers are used to declaring or injecting classes, functions, and values by which they may be used by the dependency injection mechanism.
Services may be injected in different components, modules, and other services.

Let’s begin with an example.

Step 1: First we create service using angular cli. Write following angular cli command into integrated terminal

ng g service data

It will create two files named data.service.ts and data.service.spec.ts.

Step 2: Write the following code into service.ts

In the above code block, an array “hobbies” and function “servicemethod” are defined which may be used by any components.

Step 3: Update app.module.ts (Pass the reference to newly created service and add providers)

We have to pass newly created service class name into the provider of app.module.ts. After it this services may be injectable to other components.

<script async src=”//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js”></script>
<!– big size add for between blogs –>
<ins class=”adsbygoogle”
style=”display:inline-block;width:970px;height:250px”
data-ad-client=”ca-pub-9934076637261479″
data-ad-slot=”9062913449″></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

Step4 : Update app.component.ts as following code

In above code our custom service instance “dataservice” is created and using this instance we are accessing the variable and function of angular custom service.

Step 5: Save and run using the following command

ng serve –open

Output:


Angular 5 Online Training

Angular 5 Online Training

Select your currency