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?

Shisui
  • 1,051
  • 1
  • 8
  • 23
  • 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 – bryan60 Dec 09 '19 at 21:10

1 Answers1

2
  • 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.
ng-hobby
  • 2,077
  • 2
  • 13
  • 26