1

During my testing in angular i use a lot of console logs. I don't want to repeat my self. For example if i write in the class in some angular component.

const c = console;
c.log("something");

it will work.

How can i make this c variable global, so everywhere where i write c.log it will know that this c is for this console and i will not need to write in each component in each class

const c = console;
1
  • Hi, does my answer solves your question? If so, it would help if you can accept it as the answer for Archiving. Thanks! :) Commented Aug 10, 2020 at 13:01

2 Answers 2

1

Albeit this is anti-pattern and you can really just use a service and inject it to your components as a dependency (preferred), but if you really want to do it via global variable you can do so by attaching your function / object to the global "window" object.

Every browser has a global window object available.

At the top of your main.ts file you can add this line:

declare var window: any;
window.c = console

Basically what it does is that it attaches the console object to the "c" field of window object. You can just use it then anywhere globally:

c.log("Hello World")

Do note that I added it in the main.ts file because that's where an angular application gets started. But you can add these anywhere you need (but the instantiation time will differ on where you have added it into) and it should be available globally.

Sign up to request clarification or add additional context in comments.

1 Comment

When i try c.log("something"); i get cannot find name 'c'error. I writed the coed in the main.ts file.
0

For anything that you want to access between multiple components in angular, angular services are recommended. see here https://angular.io/tutorial/toh-pt4 Essentially you can build a class with any functionality you want, then import this class into any component and use anything within that class. You could create a logging service to log any debug errors, however I would not suggestcreating a class just for basic console logging.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.