角度2:要在所有组件中使用的功能 [英] Angular 2: Functions to be used across all components

查看:80
本文介绍了角度2:要在所有组件中使用的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an angular 2 webpack project where I currently have some functions that are repeated throughout several components. I would like to inherit all of these components from a "master" class OR component (whichever works), in order to be able to call my functions from all my components that need them.

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

As an example, if I have a function foo in 3 different components:

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

我希望您将此功能移至另一个文件/类/组件:

I would like you move this function to another file/class/components:

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

并且有某种方式可以从给定的组件中调用我的foo函数.例如:

And having someway to call my foo function from my a given component. For instance:

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

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

How would I do this using Angular 2 / Typescript?

推荐答案

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

I would use a service, here's a shortened example from one of my apps:

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();
    });
  }
}

然后,您可以将此服务注入到任何东西中,这真的很有用,并且可以使事物保持干燥.

Then you can inject this service into anything, which is really useful and you keep things DRY.

您可以像这样简单地注入它:

You would simply inject it like so:

import {UtilsService} from 'app/shared';

export MyComponent {

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

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

As @aalielfeky's answer says you could use static functions.

但是,我个人会避免使用静态函数,因为静态函数无法正确测试,一旦需要在其中将要在其中一个函数中使用的构造函数中注入某些内容时,它们将使您陷入困境.由于静态函数不能使用注入的任何东西.

However, I would personally avoid static functions because they are borderline impossible to test properly as well as giving you hell once the time comes where you need to inject something in the constructor that is going to be used in one of the functions. Since static functions can't use anything that's injected.

别跟我犯同样的错误,因为您最终将不得不重写很多代码.

Don't make the same mistake as me because you will end up having to rewrite a lot of code.

这篇关于角度2:要在所有组件中使用的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆