【问题标题】:Separate Files for Functions in Angular 2/4 InjectableAngular 2/4 Injectable 中函数的单独文件
【发布时间】:2017-06-13 17:36:00
【问题描述】:

我正在编写一个可能会呈指数级增长的服务,我希望能够编写单独的文件并将它们加载到组件使用的 @Injectable 中。通常我会编写多个服务并将每个服务注入到组件中,但是我的组件已经相当庞大,我觉得如果我可以加载一个服务并处理其中的所有功能,维护起来会更容易一项服务。我希望我只是没有搜索到正确的东西,这就像导入一样简单。

总体思路是这样的:

-configfns1.ts

-configfns2.ts(包含多个我希望作为config.service提供的ts函数)

-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
  }

}

这种方法可行吗?还是我只需要继续为每个服务创建单独的服务,然后将每个服务导入到我的组件中?

【问题讨论】:

    标签: angular typescript angular2-services angular2-injection


    【解决方案1】:

    经过更多谷歌搜索后,我发现这是一个简单的打字稿导入答案。

    -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() 和 fn2() 可以正常调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2018-01-05
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2017-04-12
      相关资源
      最近更新 更多