javascript - 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.
解决方案
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){
}
}
推荐阅读
- sql - SQL Server:如何从表中创建层次结构组合
- javascript - 默认情况下自动选择单选按钮并执行“onchange”功能
- json - 如何在 Flutter 中发送 MultipartRequest 中的数组?
- testing - 迁移和测试 CLI 命令在 Visual Studio Code/VSCode 终端中不起作用
- python - 使用 tkinter 为 Python 程序创建 UI。Tkinter 中的按钮可以多次按下。如何创建“一个进程”弹出窗口?
- java - 插件更新错误“某些插件需要插件 JNA 才能安装 netbeans”
- python - 指定 Windows 路径时找不到文件错误
- javascript - 拖动桌面文档时更改鼠标光标
- jupyter-lab - 如何在 JupyterLab 中拆分和合并单元格
- azure - 用于运行生成或管道的 Azure REST API