1

I'm a little confused about when to use a service, versus when to export functions or classes.

Here's what I mean by exporting a class: See the top answer here Angular 2: Functions to be used across all components

export class Utils {
    public static log(msg:string){
        console.log(msg);
    }
}

Which is imported here and used

import {Utils} from './utils'

class parent{
   foo(s: string){
     Utils.log(s);
   }
}

class child{
   constructor(){
      Utils.log("Hello");
   }
}

And here's what I mean by exporting functions in place of a service:

export printAll(toPrint:string): void{
}

as seen in this question

Angular service vs export

What's the difference between these approaches in comparison to using a service? What's the difference between these two methods? Pros, cons? Thought process when deciding which to use?

1
  • there's a lot about this in the angular tutorial. Services are part of the dependency injection framework at angular's core. DI is useful for a number of reasons, but that's too broad a question Commented Dec 9, 2019 at 21:10

1 Answer 1

3
  • By using an exported function there is a chance to remove unused functions during the Building process and this can be taken into consideration as an advantage here.
  • By using an services you are using a construction injection pattern which is one of the best practices for implementing Inversion of Control (IOC).
  • Generally speaking based on service oriented architecture (SOA) you use an services whenever an action or service will be used many times and in angular patters usually callback to Back-end ( Rest-API, ... ) is usually implemented in services. because fetching data from back-end can be considered as an separate layer from the implementing app business in controller or component.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.