共享跨组件的service-using-typescript函数的最佳方法是什么?

时间:2017-11-05 07:12:15

标签: angular typescript

我有一些跨组件使用的TypeScript函数。 它们目前存在于它们自己的组件中(这意味着这些功能会不必要地重复)。

鉴于这些功能确实使用了服务(例如httpClient),那么最好的行动方案是什么呢?因此我们可以将它们集中到一个集中位置,并将所有这些组件用0个重复进入它们?

以下是我为使其成为基于服务的解决方案所做的工作

1. ng g s javascript-library

2. goto app.module.ts and import it

3. import { JavascriptLibraryService } from './services/javascript-library.service';

4. add it to the providers array in the app.module.ts as well.
  providers: [
    JavascriptLibraryService
  ],

5. add this code into  services/javascript-library.service.ts 

import { Injectable } from '@angular/core';

@Injectable()
export class JavascriptLibraryService {

  constructor() { }

  blp_test(input) {
    return 'Hello from Library Service';
  }

}


6. goto the component where I want to use it and and import and do dependency injection
( this is my-component.ts )

6a. import { JavascriptLibraryService } from './../../services/javascript-library.service';

6b dependency injection
constructor(
      private javascriptLibraryService: JavascriptLibraryService,
      ) {
  }


7. and finally, as the final step, try to access the function! 

ngOnInit(): void {

    blp_test(); // dead on arrival

}  

3 个答案:

答案 0 :(得分:1)

为此类功能制作Angular服务并将其导入应用模块的提供商,现在您可以在所有组件中自由使用这些功能。

答案 1 :(得分:1)

有几个选择:

  • 您可以创建一个公开方法的抽象类,并为任何共享的prop提供抽象属性
  • 服务,正如Golu Tiwari所说
  • 或者只需将其放在/shared/functions/fancy-file.ts中,然后导入这些功能。

这取决于你的用例。 :)

编辑: 根据您在下面留下的评论,抽象类似乎是最佳行动方案 - 请参阅https://angular-r8v6ac.stackblitz.io作为示例。

此示例有一个抽象类(TestImpl),它有两个共享的抽象变量。这意味着,需要在组件中定义两个抽象变量,并且没有初始值。所有受保护或公共的函数都可以在扩展此类的所有组件中使用。希望这有帮助!

答案 2 :(得分:1)

您可以考虑以下几个选项:

使用所有共享函数,类,常量等创建公共模块。

// common/DateHelper.ts
export default class DateHelper {
  static someHelperFunction(date) {...}
  static otherHelperFunction() {...}
}

然后将其导入组件中,如下所示:

import DateHelper from 'common/DateHelper';

要使用绝对路径启用导入,您需要一些Typescript compiler options。您可以在this博文中找到更多信息。

只需创建一堆常见的角度服务:

import { Injectable } from '@angular/core';

@Injectable()
export class SomeService {
}

如果你在后端使用typescript,并且你知道你将在后端和前端重用相同的代码片段,你甚至可以考虑使用自己的package.json创建通用模块。然后,可以在多个微服务之间重用相同的代码片段。

相关问题