[英]$rootScope.$broadcast usage in AngularJS
I am working with an app where I have the following line at the end of a service in service.js. 我正在使用一个应用程序,其中在service.js中服务末尾有以下行。
$rootScope.$broadcast('rootScope:Object')
Here Object is the output of an API service. 这里的Object是API服务的输出。 If I now want to use this Object in my actual app.js file, how could I use it? 如果现在我想在实际的app.js文件中使用此对象,该如何使用? What does the above line specify and how to use it in later pages? 上面的行指定了什么,以及如何在以后的页面中使用它?
Any help is appreciated. 任何帮助表示赞赏。
EDIT: 编辑:
From the given answers tried the following: 从给出的答案尝试以下方法:
In service page: 在服务页面中:
this.getobject=function(){
//http api Function call with result as response.data = resp
$rootScope.$broadcast('rootScope:resp',resp);
}
In the child scope page: 在子范围页面中:
resp=[];
$rootScope.$on('rootScope:resp',function(resp) {
$scope.resp=resp;
console.log(resp);
});
$scope.$on('rootScope:resp', function(e, params){
console.log(params); // respobject
});
Unfortunately both didn't print anything on console. 不幸的是,两者均未在控制台上打印任何内容。 Any issue with the approach? 方法有问题吗?
This line means that the $rootScope (the highest scope level) will broadcast an event named 'rootScope:Object' to all the children (your app's scopes). 这行意味着$ rootScope(最高作用域级别)将向所有子级(您的应用程序的作用域)广播名为“ rootScope:Object”的事件。
According to https://docs.angularjs.org/api/ng/type/ $rootScope.Scope, you can add parameters to the $broadcast()
function to, in your case, pass your Object. 根据https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope的说明,您可以向$broadcast()
函数添加参数,以通过您的对象。 You will have: 您将拥有:
$rootScope.$broadcast('rootScope:Object', myObject)
In your child scope, you can easily retrieve this with: 在您的子范围内,您可以轻松地通过以下方式检索此内容:
$scope.$on('rootScope:Object', function(e, params){
console.log(params); // myObject
});
Hope it helps. 希望能帮助到你。
EDIT: Here's a codepen showing loading and displaying data from an API using $broadcast/$on 编辑:这是一个代码笔 ,显示使用$ broadcast / $ on从API加载和显示数据
Not sure I understood your question but broadcast does nothing more than dispatch an event downwards to all child scopes. 不确定我是否理解您的问题,但是广播仅向所有子作用域发送事件。
So, in your service you probably want to have something like: 因此,在您的服务中,您可能希望拥有以下内容:
$rootScope.$broadcast('myEventNameHere', actualJavascriptObjectHere);
And on the place that you want to listen to this event, you will have something like this: 在您想收听此事件的地方,您将看到以下内容:
$scope.$on('myEventNameHere', function(actualJavascriptObjectHere) {
console.log(actualJavascriptObjectHere);
});
Hope that helps. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.