Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 函数使用服务工厂_Javascript_Angularjs_Ionic Framework - Fatal编程技术网

Javascript 函数使用服务工厂

Javascript 函数使用服务工厂,javascript,angularjs,ionic-framework,Javascript,Angularjs,Ionic Framework,在我的app.js中,我有以下方法: .run(function($ionicPlatform) { $ionicPlatform.ready(function() { gvi.Notifications.registerForPush(MessagesService.onNotificationResponse); }); }) 和一个工厂: .factory('MessagesService', function($scope, $q)

在我的app.js中,我有以下方法:

  .run(function($ionicPlatform) {
     $ionicPlatform.ready(function() {

        gvi.Notifications.registerForPush(MessagesService.onNotificationResponse);

     });
  })
和一个工厂:

  .factory('MessagesService', function($scope, $q) {

var messages = [];

    return {

  onNotificationResponse: function(sender, message, msgId, msgType, msgUrl) {
        console.log("myApp.onNotificationResponse:" + message + " msgUrl:" + msgUrl);

        $scope.messages.push({
          sender: sender,
          message: message,
          msgId: msgId,
          msgType: msgType,
          msgUrl: msgUrl
        });

      MessagesService.save($scope.messages);

    },
  }
 })
当我打开应用程序时,出现以下错误:

  Uncaught ReferenceError: MessagesService is not defined
如何在ionicPlatform.ready函数中使用MessagesService工厂

编辑:


我已经修复了MessageService错误,现在如何在工厂中使用$scope?

您尚未在运行中通过
MessageService
依赖项

.run(function($ionicPlatform,MessagesService) {
     $ionicPlatform.ready(function() {

        gvi.Notifications.registerForPush(MessagesService.onNotificationResponse);

     });
  })
更新:根据您的需求,您需要重构您的服务,因为服务不能引用范围。 您的服务应该向作用域公开消息数组,而不是使用在作用域上定义的消息数组

 .factory('MessagesService', function($scope, $q) {

var messages = [];

    return {

  onNotificationResponse: function(sender, message, msgId, msgType, msgUrl) {
        console.log("myApp.onNotificationResponse:" + message + " msgUrl:" + msgUrl);

        messages.push({
          sender: sender,
          message: message,
          msgId: msgId,
          msgType: msgType,
          msgUrl: msgUrl
        });

      MessagesService.save(messages);

    },
    messages:messages
  }
 })

现在,您可以使用
MessageService.messages
属性在任何控制器中引用此消息集合。

添加了该属性,然后我得到以下结果:未捕获错误:[$injector:unpr]未知提供程序:$scopeProvider您不允许将$scope作为依赖项传递给您的服务。作用域存在于html的上下文中。您需要将消息作为输入参数传递给需要保存消息的方法。如何从MessageService onNotificationResponse函数内部调用我的控制器函数?您从控制器引用服务,而不是相反。您的服务不包含对控制器的引用或直接调用控制器。你能解释一下你的情况吗?当然。当应用程序启动时,它使用回调函数(onNotificationResponse函数)调用registerForPush。registerForPush函数调用我的服务器来检查应用程序的消息。当它找到一条消息时,它调用回调函数。然后回调函数必须将消息添加到作用域中,以便可以在messages.html页面上查看该消息。