简体   繁体   English

编写全局函数以在角度的所有组件中使用

[英]Write global functions to use in all components in angular

Note : Its not for global variable but for a global common function to perform a functionality on all components注意:它不是用于全局变量,而是用于在所有组件上执行功能的全局通用函数

I am working on an angular app where I have around 400 components in different modules, almost all components have one same kind of functionality as mentioned below我正在开发一个 Angular 应用程序,我在不同的模块中有大约 400 个组件,几乎所有组件都具有如下所述的相同功能

There is a sections on many pages which shows a "How to work section" which can be closed by users and will remain closed unless they open it again, I have done it with cookies which I set on click on close or open icon but this function is written in a component and this needs to be imported in other components许多页面上有一个部分显示“如何工作”部分,用户可以关闭该部分,除非他们再次打开它,否则它将保持关闭状态,我已经使用我在单击关闭或打开图标时设置的 cookie 完成了它,但是这个函数写在一个组件中,需要在其他组件中导入

I want to create a functions somewhere which perform this functionality on click on icon and can be called without importing any component in others.我想在某处创建一个函数,该函数在单击图标时执行此功能,并且可以在不导入其他任何组件的情况下调用。

One way to do it ( as I thought ) could be create a JavaScript function in a file and load it in index file and then call this function on click on close and open icon一种方法(如我所想)可以在文件中创建一个 JavaScript 函数并将其加载到索引文件中,然后在单击关闭和打开图标时调用此函数

Not sure if this is the best way to do this.不确定这是否是最好的方法。 Hope someone will come up with a better solution.希望有人能提出更好的解决方案。

1. create your global function service, ie 'funcs.services.ts' under 'services' directory: 1.创建你的全局函数服务,即'services'目录下的'funcs.services.ts'

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

@Injectable({
  providedIn: 'root'
})

export class FuncsService {
  constructor() { }
  
  myGlobalAddFunction(a){
    return a++;
  }
  mySecondFunc(){
    // add more... and so on
  }
}

2. Import the function in your component: 2. 在你的组件中导入函数:

// your path may different 
import { FuncsService } from './../services/funcs/funcs.service';
//...
constructor(
   private funcs: FuncsService
) {}
ngOnInit(): void {
   let x = 1;
   myResult = this.funcs.myGlobalAddFunction(x);
   // Then you are expecting 2 for return value
}

3. Hope that works... :) 3.希望有效... :)

This isn't the best solution (in my opinion).这不是最好的解决方案(在我看来)。 The best solution would be to either create a service, or an utils class.最好的解决方案是创建一个服务或一个 utils 类。

But if you want to do this, I suggest you make a JS file, that you declare in your angular-cli.json file under the scripts property, containing your functions.但是如果你想这样做,我建议你制作一个 JS 文件,你在scripts属性下的 angular-cli.json 文件中声明,其中包含你的函数。

EDIT Now that you've came back to reason, here is a code sample to make utils classes.编辑现在你已经回到了理性,这里是一个代码示例,用于制作 utils 类。

export const IMG_UTILS = {
  convertPngToJpg = (picture: any) => {
    // Your logic here
  }
};

export const VIEW_MANAGER = {
  isAdblockActive = () => {
    // test if an ad-blocker is active
  }
};

You can make any utils class you want in a const, then put it into a file.您可以在 const 中创建所需的任何 utils 类,然后将其放入文件中。 Then, you can put this file in an utils folder, and request it with然后,您可以将此文件放在 utils 文件夹中,并使用

import { VIEW_MANAGER } from 'src/app/utils/view-manager';

Otherwise, you can make a service, which is handled by Angular, with a console command such as否则,您可以使用控制台命令创建一个由 Angular 处理的服务,例如

ng g s services/view-manager/view-manager

And it will behave the exact same way : you will import it in your components to use it.它的行为方式完全相同:您将在组件中导入它以使用它。

Hope this helps !希望这可以帮助 !

You can export a function that is a written in .ts file and then call it in all your components.您可以export一个用.ts文件编写的函数,然后在所有组件中调用它。

   export function myFunction(){
        // Do something
   }

And then import the function myFunction() in other components.然后在其他组件中导入函数myFunction() That works fine for me and can be useful in certain cases这对我来说很好,在某些情况下很有用

The most recommended way is to use a service and inject it whenever needed, but there is a way to have a function available globally .最推荐的方法是使用服务并在需要时注入它,但是有一种方法可以让函数全局可用。

Although I don't think it's a really good idea, you can add the function in the index.html file, then whenever you want to use it, you have to use @ts-ignore to avoid an error from being thrown.虽然我认为这不是一个好主意,但你可以在 index.html 文件中添加该函数,然后每当你想使用它时,你必须使用@ts-ignore以避免抛出错误。 eg例如

index.html索引.html

<script>
  function globalFunc(){
    alert(2)
  }
</script>

anywhere else on the app应用程序上的其他任何地方

// @ts-ignore
globalFunc();
  1. List item项目清单

Just to chime in with possibly a duplicate answer albeit more fleshed out... I have a utilities class which I use.只是为了加入可能重复的答案,尽管更加充实......我有一个我使用的实用程序类。

For example:例如:

export class Utilities {
    // Simple promise wrapper for setTimeout. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#creating_a_promise_around_an_old_callback_api
    public static Wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
}

The class is referenced in a component via the import statement:该类通过import语句在组件中引用:

import { Utilities } from 'path/to/Utilities';

And then you can call your static methods thus:然后你可以这样调用你的静态方法:

Utilities.Wait(30000)
    .then(() => DoStuff())
    .catch(() => console.log('Darn!'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM