角度2:要在所有组件中使用的功能

编程入门 行业动态 更新时间:2024-10-27 06:33:24
本文介绍了角度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:要在所有组件中使用的功能

本文发布于:2023-11-27 05:42:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636823.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:要在   组件   角度   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!