我还使用单水疗元框架研究了同一种架构。我所做的是我使用纯 Javascript(可重用 API)使用 RxJS 创建了自己的调度程序实用程序,因为任何方式 Angular 都依赖于 RxJS。所以我们可以利用它。
这是我实现的代码,您可以从任何微前端应用程序(Angular、React、Vue.js)发布和订阅。我在ts中写的代码。如果需要,您可以转换为 js。
import { Subject } from "rxjs";
(function (global: any) {
var RxDispatcher: any = function () {
return new RxDispatcher.instance();
};
RxDispatcher.prototype = {
getDispatcher: function (dispatcherName: string): Subject<any> {
if (global.subjects) {
return global.subjects[dispatcherName]
? global.subjects[dispatcherName]
: console.error(
"Unable to find the dispatcher of " +
dispatcherName +
" .Please ensure the dispatchers are properly registered."
);
}
console.error(
"Unable to find the dispatcher of " +
dispatcherName +
" .Please ensure the dispatchers are properly registered."
);
},
registerDispatchers: function (dispatchers: string[]) {
if (dispatchers) {
if (!global.subjects) {
global.subjects = {};
}
dispatchers.forEach(dispatcher => {
if (!global.subjects[dispatcher]) {
global.subjects[dispatcher] = new Subject();
}
});
}
},
dispatch: function (dispatcher: string, args?:any): void {
if (!dispatcher) {
console.error(
"Unable to dispatch message to dispatcher of " + dispatcher
);
} else {
var dispatcherInstance = this.getDispatcher(dispatcher);
if (dispatcherInstance) dispatcherInstance.next(args);
}
},
dispatchToMultiple: function (dispatchers: string[],args?:any) {
if (!dispatchers) {
console.error(
"Unable to dispatch message to dispatcher of " + dispatchers
);
}
dispatchers.forEach(subscriber => {
var dispatcherInstance = this.getDispatcher(subscriber);
if (dispatcherInstance) dispatcherInstance.next(args);
});
},
clear: function () {
delete global["subjects"];
}
};
RxDispatcher.instance = function () { };
RxDispatcher.instance.prototype = RxDispatcher.prototype;
global.RxDispatcher = RxDispatcher;
})(window);
用法
如果您在打字稿中,则必须声明
声明 var RxDispatcher: any;
注册调度员
var dispatchers=["onSendMessage"]
RxDispatcher().registerDispatchers(dispatchers); //expecting an array.
You can register multiple dispatchers at one time
发信息
RxDispatcher().dispatch("onSendMessage", {
message: "Hi"
})
订阅消息
RxDispatcher().getDispatcher("onSendMessage")
.subscribe((message) => {
console.log(message) //Output : Hi
});