javascript – Angular 6: How can we add a function to the global namespace?-ThrowExceptions

Exception or error:

My requirement is that I need to add a function to the global namespace in an Angular 6 project. This function should then be able to be called from the browser console.

How to solve:

You always have access to the window object.

As long as you add the function to the window object in a place that you know will get run when the app loads, such as app module, your function will get added to the window object.


export function myFunction() {
  console.log('Hello, World!');


import { myFunction } from './my-function';

export class AppModule { }

window['myFunction'] = myFunction;

And then from the console, run window['myFunction']();


this may not the best approach, but you have access to angular by the help of the following bootstrapping method

platformBrowserDynamic().bootstrapModule(AppModule).then(ref => {
  // Ensure Angular destroys itself on hot reloads.
  if (window['ngRef']) {
  window['ngRef'] = ref;

  // Otherwise, log the boot error
}).catch(err => console.error(err));

which is then makes it possible call sth like this from browser console



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

@Injectable({ providedIn: "root" })
export class TestService {
  sayHelloWorld() {
    console.log("Hello World");

Leave a Reply

Your email address will not be published. Required fields are marked *