$ rootScope.$ AngularJS中的广播使用情况

use*_*983 1 javascript angularjs angularjs-directive angularjs-rootscope

我正在使用一个应用程序,我在service.js服务结束时有以下行.

$rootScope.$broadcast('rootScope:Object') 
Run Code Online (Sandbox Code Playgroud)

这里Object是API服务的输出.如果我现在想在我的实际app.js文件中使用此Object,我该如何使用它?上面的行指定了什么以及如何在以后的页面中使用它?

任何帮助表示赞赏.

编辑:

从给定的答案尝试以下:

在服务页面中:

this.getobject=function(){
//http api Function call with result as  response.data = resp 
$rootScope.$broadcast('rootScope:resp',resp);
}
Run Code Online (Sandbox Code Playgroud)

在子范围页面中:

resp=[];
$rootScope.$on('rootScope:resp',function(resp) {
          $scope.resp=resp;
          console.log(resp);

      });
$scope.$on('rootScope:resp', function(e, params){
             console.log(params); // respobject
        });
Run Code Online (Sandbox Code Playgroud)

不幸的是,两者都没有在控制台上打印.这个方法有什么问题吗?

Jul*_*lCh 6

这一行意味着$ rootScope(最高范围级别)将向所有子项(您的应用程序的范围)广播名为"rootScope:Object"的事件.

根据https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope,您可以在$broadcast()函数中添加参数,以便传递您的Object.你将会有:

$rootScope.$broadcast('rootScope:Object', myObject)
Run Code Online (Sandbox Code Playgroud)

在您的子范围中,您可以使用以下方法轻松检索:

$scope.$on('rootScope:Object', function(e, params){
     console.log(params); // myObject
});
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.

编辑:这是一个codepen,显示使用$ broadcast/$ on从API加载和显示数据