首页 > 解决方案 > How can I declare a global function to call an Angular service from the browser console?

问题描述

We have a requirement that we'd like to develop a "mini" testing framework for use within our Angular application. The point of the framework is to be able to manipulate API calls to alter the response body and status code in order to trip various error handlers within our application and make sure the application is responding correctly to errored API calls.

To do this I have been researching how to call Angular services from outside of Angular. This article describes how it is possible to create a service and then trigger it from outside Angular by calling the window.fireAngularEvent('sampleEventName', args) function.

However when I tried to do this via the browser, I get the following: Uncaught TypeError: window.fireAngularEvent is not a function

Here is my Angular service

export class GlobalApiTestingFrameworkService {

  constructor() {
    window['fireAngularEvent'] = (eventName, args) => {
      console.log('fireAngularEvent : ' + eventName + ' : ' + args);
    }
  }
}

What do I need to do to be able to call the window.fireAngularEvent function? Do I need to define it outside of Angular within its own JS file? If so, what exactly do I include within the function body to allow it to communicate with the service? The article I linked isn't very clear.

标签: javascriptangular

解决方案


The problem is due to the space in window['fireAngularEvent '] replace the defintion with window['fireAngularEvent'] and you'll be able to call window.fireAngularEvent without any issue.

Make sure that your service is instantiated at least one time.

To be sure You can use for example your service in AppComponent like that:

export class AppComponent  {
    constructor(private globalApiTestingFrameworkService: GlobalApiTestingFrameworkService){
    }
}

推荐阅读