AngularJS,在外部事件上重新初始化(更新页面)

时间:2018-10-29 18:22:54

标签: angularjs firebase phonegap

打开聊天页面消息后,我有angularjs移动应用程序:

window.FirebasePlugin.onNotificationOpen(function(data) {
    // some code here to reload new chat messages
});

现在通过外部事件,我需要以某种方式重新初始化控制器(加载新消息):

class Parent { }

class Child {
    unowned var parent: Parent // every child needs a parent

    init(parent: Parent) {
        self.parent = parent
    }
}

var parent: Parent? = Parent()
let child = Child(parent: parent!) // let's pretend the forced unwrap didn't happen
parent = nil // let's deallocate this bad parent
print(child.parent) // BOOM!!!, crash

有没有不肮脏的方法来重新初始化控制器或调用控制器功能?

1 个答案:

答案 0 :(得分:1)

您可以从Firebase插件创建可注入服务。然后将该服务注入到控制器中,并调用获取消息的函数:

myApp
  .factory('firebase', function ($window) {
      return $window.FirebasePlugin;
  });

myApp.controller('ChatControllerGlobal', function ($scope, $http, firebase) {
  getMessages();

  firebase.onNotificationOpen(function (data) {
    getMessages();
  });

  function getMessages() {
    $http({
      method: 'POST',
      url: serverURL + '&act=get_chat',
      withCredentials: true,
    }).then(function successCallback(data) {
      $scope.messages = data.data;
      $scope.loader = false;
      $scope.content = true;
    });
  }
});

通过这种方法,您可以在单元测试中模拟firebase服务。