Sharing Data Between Angular Elements and Non-Angular Components
Explain how to pass data between Angular Elements and components of non-Angular libraries using a shared global state or a pub-sub mechanism.
// Define a simple PubSub Service for communication
var PubSub = {
events: {},
subscribe: function(eventName, fn) {
this.events[eventName] = this.events[eventName] || [];
this.events[eventName].push(fn);
},
unsubscribe: function(eventName, fn) {
if (this.events[eventName]) {
for (var i = 0; i < this.events[eventName].length; i++) {
if (this.events[eventName][i] === fn) {
this.events[eventName].splice(i, 1);
break;
}
}
}
},
publish: function(eventName, data) {
if (this.events[eventName]) {
this.events[eventName].forEach(function(fn) {
fn(data);
});
}
}
};
Defines a PubSub service that can be used for publishing events and subscribing to them, enabling communication between distinct parts of an application.
// Usage from within an Angular component or service
class SomeAngularComponent {
constructor() {
PubSub.subscribe('nonAngularEvent', this.handleData);
}
handleData(data) {
// Do something with the data received from non-Angular component
}
ngOnDestroy() {
// Unsubscribe when the component is destroyed
PubSub.unsubscribe('nonAngularEvent', this.handleData);
}
}
An Angular component subscribes to events using the PubSub service and defines a method to handle incoming data. It also ensures to unsubscribe when the component is destroyed to prevent memory leaks.
// Usage from a non-Angular component or library
document.querySelector('#some-button').addEventListener('click', function() {
var data = { value: 'example data' };
// Publish an event with some data
PubSub.publish('nonAngularEvent', data);
});
A non-Angular component, such as a vanilla JS event listener on a button, publishes an event through the PubSub system, passing data to any subscribers.
// Using shared global state (assuming the existence of a global state object)
window.sharedState = { data: null };
// Angular component setting shared data
class SomeAngularComponent {
setData(value) {
window.sharedState.data = value;
}
}
An Angular component sets data on a shared global state object that both Angular and non-Angular parts of an application can access.
// Non-Angular component reading shared data
function readSharedData() {
return window.sharedState.data;
}
// Usage
var theData = readSharedData();
console.log('Shared data:', theData);
A non-Angular component reads from the shared global state, allowing it to access data set by Angular components.