Reputation: 3351
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
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
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
Not sure if this is the best way to do this. Hope someone will come up with a better solution.
Upvotes: 27
Views: 43114
Reputation: 87
if you want to use it without inject in constructor and import in each time, just set all global functions as static
static sortById(data : any[]):any[] {
return data.sort((a, b) => parseFloat(a.id) - parseFloat(b.id))
}
then use it anywhere in your project
GlobalHelper.sortById(data)
Upvotes: 1
Reputation: 986
I use this solution for calling the google analytics gtag function (which is a global function on the Window object) in my services:
I add this to my AppComponent:
export class AppComponent {
... component stuff
}
declare global {
interface Window {
gtag(arg0: string, arg1: string): void;
}
}
Then in all areas where you need to call that function, add the reference to window:
export class MyService {
myMethod(): void {
// do stuff...
// then send event
window.gtag('event', 'details');
}
}
Upvotes: 0
Reputation: 11699
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 { Utilities } from 'path/to/Utilities';
And then you can call your static methods thus:
Utilities.Wait(30000)
.then(() => DoStuff())
.catch(() => console.log('Darn!'));
I would tend to use RxJs but I've written it this way to keep things a little cleaner.
Upvotes: 6
Reputation: 2928
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.
e.g
index.html
<script>
function globalFunc(){
alert(2)
}
</script>
anywhere else on the app
// @ts-ignore
globalFunc();
Upvotes: 2
Reputation: 304
1. create your global function service, i.e. 'funcs.services.ts' under 'services' directory:
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:
// 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... :)
Upvotes: 22
Reputation:
This isn't the best solution (in my opinion). The best solution would be to either create a service, or an utils class.
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.
EDIT Now that you've came back to reason, here is a code sample to make utils classes.
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. Then, you can put this file in an utils folder, and request it with
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
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 !
Upvotes: 12
Reputation: 1085
You can export
a function that is a written in .ts
file and then call it in all your components.
export function myFunction(){
// Do something
}
And then import the function myFunction()
in other components. That works fine for me and can be useful in certain cases
Upvotes: 15