[英]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.我们需要开发一个“迷你”测试框架,以便在我们的 Angular 应用程序中使用。 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.
该框架的重点是能够操纵 API 调用来更改响应主体和状态代码,以便在我们的应用程序中触发各种错误处理程序并确保应用程序正确响应错误的 API 调用。
To do this I have been researching how to call Angular services from outside of Angular.为此,我一直在研究如何从 Angular 外部调用 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. 本文描述了如何创建一个服务,然后通过调用
window.fireAngularEvent('sampleEventName', args)
函数从 Angular 外部触发它。
However when I tried to do this via the browser, I get the following: Uncaught TypeError: window.fireAngularEvent is not a function
但是,当我尝试通过浏览器执行此操作时,我得到以下信息:
Uncaught TypeError: window.fireAngularEvent is not a function
Here is my Angular service这是我的 Angular 服务
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?我需要做什么才能调用 window.fireAngularEvent 函数? Do I need to define it outside of Angular within its own JS file?
我是否需要在它自己的 JS 文件中在 Angular 之外定义它? 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.该问题是由于在空间
window['fireAngularEvent ']
替换把定义window['fireAngularEvent']
你就能够调用window.fireAngularEvent没有任何问题。
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:可以肯定的是,您可以像这样在 AppComponent 中使用您的服务:
export class AppComponent {
constructor(private globalApiTestingFrameworkService: GlobalApiTestingFrameworkService){
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.