1

In angular we need to create @Injactable service class and provide it to our project.

In theory we can import es6 module that executes as singleton service as well.

Except that this is not "the angular way", why this method is not so common?

angular way

import { Injectable } from '@angular/core';
@Injectable()
export class fo {
   getFo():{
   }
}

es6 way

    const bla = []
    const fo() => {return bla}
    export {
        fo
    }
1
  • Your two examples have nothing in common. Commented Apr 5, 2017 at 7:15

1 Answer 1

2

@Injectable() is only necessary when your service is injecting other services.

Example:

@Injectable()
export class fo {
   constructor(private myOtherService: MyOtherService){}
}

Other than that you are right that it's practically the same thing for returning a const. However as you would appreciate it is good practice to add the annotation and the logic.

Source: https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#-injectable-

Technically, the @Injectable()decorator is only required for a service class that has its own dependencies


Shortly, we use @Injectables to get/set data and communicate between components and throughout our app that are part of our dependency injection tree. There's a more in-depth guide on official docs on why you should use @Injectable().

Why @Injectable()?

@Injectable() marks a class as available to an injector for instantiation. Generally speaking, an injector reports an error when trying to instantiate a class that is not marked as @Injectable().

Source: https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#why--injectable--

Sign up to request clarification or add additional context in comments.

4 Comments

"Other than that you are right that it's practicaly the same thing" Absolutely not.
@zeroflagL yep that was an exaggerated statement and I regret I wrote that :D but since OP was only using the service to return a const; for this usage I suppose they it is practically the same thing sir. And of course I assumed OPs getFo() method is returning the same const as in the second example.
You are right that in this particular case it probably wouldn't matter, but it's not a real world example. The example in the question is only there to illustrate the point and the answer should not be limited to that.
@zeroflagL I will try to give more details on this subject but as you would appreciate it will require me to also explain dependency injection system of Angular and so on. I tried to give a reasonable resouce to read with my last edit. I appreciate your criticism :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.