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.

my-function.ts

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

app.module.ts

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

@NgModule()
export class AppModule { }

window['myFunction'] = myFunction;

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

###

https://stackblitz.com/edit/angular-ngref-access-problem

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'].destroy();
  }
  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

ngRef._providers[19].sayHelloWorld()

test.service.ts

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 *