加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:24:52 所属栏目:安全 来源:网络整理
导读:我有一个有角度的2 webpack项目,我目前有一些功能在几个组件中重复.我想从“master”类OR组件(无论哪种方法)继承所有这些组件,以便能够从我需要它们的所有组件中调用我的函数. 举个例子,如果我在3个不同的组件中有一个函数foo: foo(s: string){ console.log
我有一个有角度的2 webpack项目,我目前有一些功能在几个组件中重复.我想从“master”类OR组件(无论哪种方法)继承所有这些组件,以便能够从我需要它们的所有组件中调用我的函数.

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

foo(s: string){
  console.log(s);
}

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

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

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

class child{
  constructor(){
    foo("Hello");
  }
}

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

我会使用一个服务,这是我的一个应用程序的缩短示例:
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();
    });
  }
}

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

你只需要像这样注入它:

import {UtilsService} from 'app/shared';

export MyComponent {

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

编辑:

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读