I am working with an app where I have the following line at the end of a service in service.js.
$rootScope.$broadcast('rootScope:Object')
Here Object is the output of an API service. If I now want to use this Object in my actual app.js file, how could I use it? 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).
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.
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