全局函数中的Angular.js依赖项注入 [英] Angular.js dependency injection in global function

查看:85
本文介绍了全局函数中的Angular.js依赖项注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用angular.js编写cordova应用程序。当我使用PushPlugin向用户发送推送通知时。我已经这样注册用户电话:

  var pushNotification = window.plugins.pushNotification; 
pushNotification.register(successHandler,errorHandler,{ senderID:[gmc_project_number], ecb: app.onNotificationGCM});

我传递的最后一个参数是 app.onNotificationGCM 这是我收到通知时调用的函数。



这是该函数的实现:

  app.onNotificationGCM =函数(e){
开关(e.event){
案例已注册:
if(e.regid .length> 0){
console.log( Regid + e.regid);
警报(注册ID =’+ e.regid);
}
休息;

案例消息:
//这是实际的推送通知。其格式取决于推送服务器
警报中的数据模型( message =’+ e.message + msgcnt =’+ e.msgcnt));
休息时间;

情况错误:
警报( GCM错误= + e.msg);
休息时间;

默认值:
警报(发生了未知的GCM事件);
休息时间;
}
};

我必须按顺序将其添加到全局变量(在本例中为angular.module)中



这是我从 https://github.com/phonegap-build/PushPlugin/issues/309


因为Android JAVA代码调用了一个名为sendJavascript()的函数(我在
LogCat中看到了它),该函数包含一个字符串,其中
包含一个名为onNotificationGCM(Json)的函数在
文档中,因此,如果您在 onDeviceReady中加载该函数,则仅当设备准备就绪时才可用
,而并不总是像
应该那样(注册需要花费一些时间)秒回来)


现在它可以正常工作了。问题是我想在 onNotificationGCM 内调用工厂并从中进行http调用。目前,我不知道如何注入工厂。
我尝试将 onNotificationGCM 函数分配给 $ rootScope ,但在响应中无法访问。 p>

有没有办法在这个全局函数内注入工厂?
是否有另一种方法可以实现此功能,也许在 app.config()内部?

解决方案

如果您有Angular $ injector ref ),您可以轻松地通过依赖项注入来调用函数:

  $ injector.invoke([ $ http,myfunction]); 

例如,您可以将整个函数包装为:

  app.onNotificationGCM =函数(e){
$ injector.invoke([ $ http,function($ http){
/ /您的代码在这里...这将是Angular
}]注入的依赖项;
};

您肯定会想调用 $ apply()- $ http 调用之前不会运行,因此实际上代码应该是:

  app.onNotificationGCM =函数(e){
$ injector.invoke([ $ http, $ rootScope,function($ http,$ rootScope){
$ rootScope 。$ apply(function(){
//您的代码在这里...它将由Angular
//依赖注入,并在摘要循环
}中正确调用));
}]);
};

那只是一部分。现在的问题是,如何为应用程序保留适当的 $ injector



如果手动引导,然后 angular.bootstrap ref )返回注射器。只需将其保存在(全局变量)中即可。



您可能会使用 ng-app 。然后,您将不得不识别包含 ng-app 的元素,并调用 angular.element.injector 参考-查找 jQuery / jqLit​​e Extras)。例如,如果 ng-app < body> 中:

  //在代码OUTSIDE Angular 
var $ injector = angular.element(document.body).injector();


I am writing a cordova application with angular.js. When I use the PushPlugin to send push notifications to the user. I have register the user phone like this:

var pushNotification = window.plugins.pushNotification;
    pushNotification.register(successHandler, errorHandler, { "senderID": [gmc_project_number], "ecb": "app.onNotificationGCM" });

The last parameter that I pass is app.onNotificationGCM this is a function that is called when I receive a notification.

This is the implementation of that function:

 app.onNotificationGCM = function (e) {
    switch (e.event) {
        case 'registered':
            if (e.regid.length > 0) {
                console.log("Regid " + e.regid);
                alert('registration id = ' + e.regid);
            }
            break;

        case 'message':
            // this is the actual push notification. its format depends on the data model from the push server
            alert('message = ' + e.message + ' msgcnt = ' + e.msgcnt);
            break;

        case 'error':
            alert('GCM error = ' + e.msg);
            break;

        default:
            alert('An unknown GCM event has occurred');
            break;
    }
};

I have to add it in a global variable (in this case the angular.module), in order for it to be accessible when the response is returned.

This is the explanation that I got from https://github.com/phonegap-build/PushPlugin/issues/309

Because the Android JAVA code calls a function (I saw it in the LogCat) called sendJavascript() this function contain a string that contain the function onNotificationGCM(Json) that is called in the document so if you load the function in the "onDeviceReady" it will be avalaible only when the device is ready and not always like is supposed to be (the registrration takes a few seconds to come back)

As it is now it works just fine. The problem is that I want to call a factory and make an http call from it inside onNotificationGCM. Currently I don't know how to inject the factory. I tried assigning the onNotificationGCM function to $rootScope but it was not accessible on the response.

Is there a way to inject a factory inside this global function? Is there another way to implement this, perhaps inside app.config()?

解决方案

If you have an Angular $injector (ref) for your application, you can easily call a function with dependency injection:

$injector.invoke(["$http", myfunction]);

You could, for instance, wrap the entire function as:

app.onNotificationGCM = function (e) {
    $injector.invoke(["$http", function($http) {
        // your code here... it will be dependency injected by Angular
    }]);
};

You will most definitely want to call $apply() - $http calls will not run before, so actually the code should be:

app.onNotificationGCM = function (e) {
    $injector.invoke(["$http", "$rootScope", function($http, $rootScope) {
        $rootScope.$apply(function() {
            // your code here... it will be dependency injected by Angular
            // ... AND called properly in a digest cycle
        });
    }]);
};

That is only part one. Now the question is how do you get hold of the proper $injector for your application?

If you bootstrap manually, then angular.bootstrap (ref) returns the injector. Just keep it in a (global?) var.

You probably use ng-app. Then you will have to identify the element that contains ng-app somehow and call angular.element.injector (ref - look for "jQuery/jqLite Extras"). E.g., if ng-app is in the <body>:

// in code OUTSIDE Angular
var $injector = angular.element(document.body).injector();

这篇关于全局函数中的Angular.js依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆