javascript - ionicPlatform.ready() 函数使用服务工厂

标签 javascript angularjs ionic-framework

在我的 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 工厂?

编辑:

我已经修复了 MessagesService 错误,现在如何在工厂中使用 $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 属性在任何 Controller 中引用此消息集合。

关于javascript - ionicPlatform.ready() 函数使用服务工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23754892/

相关文章:

javascript - 将嵌套 json 中的值检索到 ng-repeat 中

jquery - HttpStatusCodeResult.StatusDescription 有多可靠?

javascript - AngularJS : drag-n-drop directive not working

angular - Native Storage Error,不显示如下画面

ionic-framework - 如何在 Ionic 中实现媒体查询

javascript - 为什么我对 server.js 的 get 请求返回 ionic - cloud 9 上的实际文件

java - 菜单错误的解决方法

javascript - 在鼠标悬停事件上使用 Javascript 隐藏内容

c# - 删除时出现 WebAPI 405 错误

android - 构建 Ionic 应用程序时出错 : Failed to execute aapt (CordovaLib:processDebugResources)