在我的 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/