我可以在Angular组件之外使用AngularJS的$ q吗?

时间:2022-08-23 11:37:24

I am writing a browser app, and I have a file that creates an object and initializes it. The app is written in AngularJS, but the file in question is plain Javascript, outside the Angular ecosystem.

我正在编写一个浏览器应用程序,我有一个创建对象并初始化它的文件。该应用程序是用AngularJS编写的,但有问题的文件是在Angular生态系统之外的纯Javascript。

I want to use promises in that file, but since Angular contains an an implementation of Q, I'd rather just use that than bring in another library.

我想在该文件中使用promises,但由于Angular包含Q的实现,我宁愿使用它而不是引入另一个库。

I am also using RequireJS.

我也在使用RequireJS。

So, is there a way to use $q in a non-Angular file?

那么,有没有办法在非Angular文件中使用$ q?

1 个解决方案

#1


9  

You can do this by using the angular.injector() method which returns an $injector function that can be injected with dependencies that you need (e.g. $http, $q) through its invoke() method.

您可以使用angular.injector()方法执行此操作,该方法返回$ injector函数,该函数可以通过其invoke()方法注入您需要的依赖项(例如$ http,$ q)。

DEMO

Something like this:

像这样的东西:

angular.injector(['ng']).invoke(['$q', function($q) {

  $q.when('hello world').then(function(message) {
    window.alert(message);
  });

}]);

Note that the array passed to angular.injector() is a list of modules, I included the ng module because that is where the AngularJS core dependencies are located.

请注意,传递给angular.injector()的数组是一个模块列表,我包含了ng模块,因为这是AngularJS核心依赖项所在的位置。

#1


9  

You can do this by using the angular.injector() method which returns an $injector function that can be injected with dependencies that you need (e.g. $http, $q) through its invoke() method.

您可以使用angular.injector()方法执行此操作,该方法返回$ injector函数,该函数可以通过其invoke()方法注入您需要的依赖项(例如$ http,$ q)。

DEMO

Something like this:

像这样的东西:

angular.injector(['ng']).invoke(['$q', function($q) {

  $q.when('hello world').then(function(message) {
    window.alert(message);
  });

}]);

Note that the array passed to angular.injector() is a list of modules, I included the ng module because that is where the AngularJS core dependencies are located.

请注意,传递给angular.injector()的数组是一个模块列表,我包含了ng模块,因为这是AngularJS核心依赖项所在的位置。