Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service vs Class instances in angular 2

Tags:

angular

I'm newbie to angular 2. I had started working over services in angular 2. I understood that we need to decorate the class with @Injectable() to make it as a service as like below.

import {Injectable} from '@angular/core'
@Injectable()
export class MyFirstServiceClass{
  SayHelloToService(){
  alert('Service called');
  return 'Hello, welcome your service...';
  }
}

After that we are accessing it from the constructor of our component class as like below :

import { Component } from '@angular/core';
import {MyFirstServiceClass} from './FirstService.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(private  servtest : MyFirstServiceClass )
  {    
      this.title =  servtest.SayHelloToService();
  }
}

My template code :

<div style="text-align:center">
  {{title}}
  <button id='btn' (click)='servtest.SayHelloToService()'>Click Me ! 
</button>
</div>

I was able to see the result even on button click and on load of page as component creation completes so no problem.

But, I was able to access even directly without any kind of @injectable just by creating the instance of that class 'MyFirstServiceClass' as like below :

export class AppComponent {
title = 'app';
 servtest = new MyFirstServiceClass();
   func1(){
   this.title= this.servtest.SayHelloToService();
   } 
}

I'm not getting how they both are differ to each other.

like image 319
Srikanth Reddy Avatar asked Dec 18 '22 01:12

Srikanth Reddy


1 Answers

The @Injectable() decorator does not make a class a service. Any class can be a service. Whether or not it behaves like a service is defined by how you register it. If it is registered in the provider array of a module or component, it is a service.

  providers: [
    ProductService,
    ProductEditGuard,
    ProductParameterService
  ]

Adding the @Injectable() is only required to tell a service that it needs to inject other services. Like this:

@Injectable()
export class ProductService {
    private productsUrl = 'api/products';
    private products: IProduct[];

    constructor(private http: HttpClient) { }

    // ...
}

Trying the above code without the @Injectable() decorator generates a syntax error: Uncaught (in promise): Error: Can't resolve all parameters for ProductService

NOTE: It is consider "best practice" to add the @Injectable() decorator to every service so if later developers do inject a service into the service it won't generate an error.

like image 174
DeborahK Avatar answered Dec 28 '22 11:12

DeborahK