Search code examples
angulartypescriptangular2-servicesangular2-injection

Separate Files for Functions in Angular 2/4 Injectable


I'm writing a service which is likely going to grow exponentially, and I would like to be able to write separate files and load them into an @Injectable that a component uses. Normally I would just write multiple services and inject each one into the component, but my component is already fairly hefty and I feel like it'd be easier to maintain if I could just load one service and take care of all of the function within this one service. I'm hoping that I've just not googled the right things, and this is as simple as an import.

General idea would be something along these lines:

-configfns1.ts

-configfns2.ts (contain multiple ts functions I want available as config.service)

-config.service.ts

import { Injectable } from '@angular/core'
//{{Possibly import functions here}}

@Injectable ()
export class ConfigService {

  //{{Or possibly load within the class}}

}

-config-view.component.ts

import { Component, OnInit } from '@angular/core';
import { ConfigService } from '../services/config.service';

@Component({
  selector: 'app-config-view',
  templateUrl: './config-view.component.html',
  styleUrls: ['./config-view.component.scss']
})

export class ConfigViewComponent implements OnInit {

  constructor(private configService: ConfigService){  }

  ngOnInit() {
          this.configService.configfn1(); //<---This would be a function loaded from configfns1.ts, and injected from config.service.ts
      })

  onClick() {
    this.configService.configfn2(); //Another fn loaded from configfns2.ts
  }

}

Is this method possible? Or will I just need to go ahead and create separate services for each one, and import each one into my component?


Solution

  • After more googling I found this was a simple typescript import answer.

    -config.service.ts

    import { Injectable } from '@angular/core'
    import * as configFns1 from './configfns1.ts'
    import * as configFns2 from './configfns2.ts'
    
    @Injectable ()
    export class ConfigService {
    
      fn1() {
        configFns1.fn1();
      }
    
      fn2() {
        configFns2.fn2();
      }
    }
    

    fn1() and fn2() can be called as normal.