每当用户按下信号推送服务器发送的通知时,我希望我的应用程序自动刷新以从API检索最新数据。下面是我的示例代码,我无法从App.js调用控制器函数到dorefresh()。或者还有其他解决方法可以让我检索最新数据吗?
App.js
angular.module('starter', ['ionic','starter.controllers'])
.run(function($ionicPlatform, $rootScope) {
$ionicPlatform.ready(function() {
// Enable to debug issues.
// window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
var notificationOpenedCallback = function(jsonData) {
//alert("Notification received:\n" + JSON.stringify(jsonData));
//console.log('didReceiveRemoteNotificationCallBack: ' + JSON.stringify(jsonData));
$rootScope.openedFromNotification = true;
alert($rootScope.openedFromNotification);
$ionicHistory.clearCache();
$window.location.reload(true);
};
// Update with your OneSignal AppId and googleProjectNumber before running.
window.plugins.OneSignal.init("xxxxxxxxxxxxxxxx",
{googleProjectNumber: "xxxxxxxxxxxxxx"},
notificationOpenedCallback);
});
})
Controller.js
angular.module('starter.controllers',['ionic'])
.controller('MainCtrl', function($scope, $rootScope, $http) {
$http.get("localhost/test/getitem.php")
.success(function (response)
{
$scope.items = response;
});
$scope.doRefresh = function() {
console.log("Refreshing!");
$http.get("localhost/test/getitem.php")
.success(function(response) {
$scope.items = formatData(response);
})
.finally(function() {
$scope.$broadcast('scroll.refreshComplete')
})
};
的index.html
<ion-refresher pulling-text="Pull to refresh" on-refresh="doRefresh()">
</ion-refresher>
<div class="item">
<h2 style="text-align:center; font-size:25px; font-weight:">{{item.name}}</h2>
</div>
答案 0 :(得分:3)
您可以在notificationOpenedCallback
:
var notificationOpenedCallback = function(jsonData) {
//alert("Notification received:\n" + JSON.stringify(jsonData));
//console.log('didReceiveRemoteNotificationCallBack: ' + JSON.stringify(jsonData));
$rootScope.openedFromNotification = true;
alert($rootScope.openedFromNotification);
// $ionicHistory.clearCache();
// $window.location.reload(true);
$rootScope.$broadcast('app:notification', {refresh: true});
};
如您所见,我已创建自定义事件app:notification
并使用$rootScope
将其广播($broadcast
)到子范围。
我已经附加了一个对象,其中包含您的接收者可以使用的一些信息。
现在在您的控制器中,您可以使用$scope.$on
拦截事件并调用您的刷新功能:
angular.module('starter.controllers',['ionic'])
.controller('MainCtrl', function($scope, $rootScope, $http) {
$scope.$on('app:notification', function(event, data) {
console.log(data);
if (data.refresh)
{
$scope.doRefresh();
}
});
});
注意:
您真的不需要在此处清除缓存$ionicHistory.clearCache();
。