Angular 2:要在所有组件中使用的函数

Van*_*iza 15 inheritance class typescript angular2-components angular

我有一个有角度的2 webpack项目,我目前有一些功能在几个组件中重复.我想从"master"类OR组件(无论哪种方法)继承所有这些组件,以便能够从我需要它们的所有组件中调用我的函数.

例如,如果我在3个不同的组件中有一个函数foo:

foo(s: string){
  console.log(s);
}
Run Code Online (Sandbox Code Playgroud)

我希望您将此函数移动到另一个文件/类/组件:

class parent{
  foo(s: string){
    console.log(s);
  }
}
Run Code Online (Sandbox Code Playgroud)

并且从某个给定的组件调用我的foo函数.例如:

class child{
  constructor(){
    foo("Hello");
  }
}
Run Code Online (Sandbox Code Playgroud)

我如何使用Angular 2/Typescript做到这一点?

Chr*_*odz 40

我会使用一个服务,这是我的一个应用程序的简短示例:

import {Injectable} from '@angular/core';
import * as _ from 'lodash';

@Injectable()

export class UtilsService {

  findObjectIndex(list: any[], obj: any, key: string): number {

    return _.findIndex(list, function(item) {
      return obj[key] === item[key];
    });
  }

  findObjectByQuery(list: any[], key: string, query: string): any {

    return _.find(list, function(item) {
      return item[key].toLowerCase() === query.toLowerCase();
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以把这个服务注入任何东西,这是非常有用的,你可以保持干燥.

你只需要像这样注入它:

import {UtilsService} from 'app/shared';

export MyComponent {

  constructor(private utils: UtilsService) {
    utils.findObjectIndex([], {}, 'id'); // just an example usage
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

正如@ aalielfeky的回答所说,你可以使用静态函数.

但是,我个人会避免使用静态函数,因为它们无法正常测试,并且一旦到了需要在构造函数中注入某些函数的地方,就会让你下地狱.由于静态函数不能使用注入的任何东西.

不要犯与我相同的错误,因为你最终不得不重写很多代码.

  • @ pro.mean这样做将导致这些功能在服务之外无法使用。所以不行。 (2认同)
  • @ pro.mean这是因为它是可注射的,您可以按照您所说的进行注射。即使在注入服务之后,将私有功能添加到这些功能也不会使其可用。 (2认同)

小智 15

您可以创建所有方法都是静态的类

export class Utils {
    public static log(msg:string){
        console.log(msg);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,只需将其导入您想要使用的位置

import {Utils} from './utils'

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

class child{
   constructor(){
      Utils.log("Hello");
   }
}
Run Code Online (Sandbox Code Playgroud)