Summary of the article
Practice micro Front-end – Angular + Qiankun – From 0 to 1
Practice micro Front-end – Angular + Qiankun – Communication between Applications
Working on a micro front End – Angular + Qiankun – Nginx release is already testing
Making portal
Welcome to discuss technical issues
The introduction
Hello ~
This article is an application to application communication based on the qiankun + Single-SPA micro front-end Best Practices series. By default, you have read from 0 to 1. If you have not read, you can click the link above.
This article will share how to use qiankun + single-spa and how to send or subscribe to globalState data capture in the main application or sub-application.
Actions
communication
The initGlobalState method is provided internally to register MicroAppStateActions instances for communication, which have three methods:
setGlobalState
Set:globalState
– When setting a new value, it will be executed internallyShallow check
If detectedglobalState
Changes trigger notifications to all of themThe observer
Function.onGlobalStateChange
Register:The observer
Function-responseglobalState
Changes inglobalState
This is triggered when changes occurThe observer
Function.offGlobalStateChange
Cancelled:The observer
Function – The instance is no longer respondingglobalState
Change.
Let’s draw a picture to help you understand (see the picture below)
As we can see from the figure above, we can register observers to the observer pool and then modify the globalState to trigger all observer functions to communicate between components.
Actual combat tutorial
Using github as an example (with portal) (using Angular10 as the base for the main application and connecting to the Angular10 sub-application), we will introduce how to use Qiankun to complete the communication between applications.
Clone case – pull the code to the local, run the project to see the actual effect.
Tasks for the main application
First, we register an instance of MicroAppStateActions in the main application and export it as follows:
import { MicroAppStateActions, initGlobalState } from 'qiankun'
// Initialize state
/** If the current application is listening for global status and any changes trigger callback, fireImmediately = true trigger callback */
export const Actions: MicroAppStateActions = initGlobalState({
micro: 'Master reference load complete! ',})Copy the code
After registering the MicroAppStateActions instance, use the actions.service.ts in shared. We use the service service to encapsulate the microservice observer and publish functions as follows:
@Injectable({
providedIn: 'root',})export class ActionsService {
private actions: MicroAppStateActions = Actions
constructor() {}
/** If the current application is listening for global status and any changes trigger callback, fireImmediately = true trigger callback */
onGlobalStateChange() {
return this.actions.onGlobalStateChange
}
/** Set global state by level 1 attribute. Only existing level 1 attribute */ can be modified in micro applications
setGlobalState(data) {
this.actions.setGlobalState(data)
}
}
Copy the code
Ts: app.module.ts: app.module.ts: actions.service.ts: app.module.ts: actions.
@NgModule({ declarations: [AppComponent], imports: [ BrowserModule, BrowserAnimationsModule, IconsProviderModule, FormsModule, HttpClientModule, RouterModule, Providers: [ActionsService, {provide: NZ_I18N, useValue: en_US }], bootstrap: [AppComponent], }) export class AppModule {} }Copy the code
The next step is to use the Qiankun microservice in the main application to load the sub-application and use the observer and publish functions to observe it as follows:
export class WelcomeComponent implements OnInit { microApp @ViewChild('mango_iview') containerRef: ElementRef mangoState count = 1 constructor(private actions: ActionsService) {} ngOnInit() { this.actions.onGlobalStateChange()((state, Prev) => {this.mangoState = state console.warn(' master get-state -->' + this.mangoState) console.warn(' master get-prev -->' + Prev)})} ngAfterViewInit(): void {// loadMicroApp = loadMicroApp({name: 'mangore-iview ', entry: '//localhost:4300', container: Enclosing containerRef nativeElement,})} / * * * * / release function setGlobal (data) {this. Actions. SetGlobalState (data) enclosing count++}}Copy the code
HTML is pretty neat
<button nz-button nzType="primary" (click) ="setGlobal({micro:'我是主应用',id:count})">I'm going to send the main application variable</button>
<div #mango_iview id="mango-iview"></div>
Copy the code
Tasks for subapplications
We have completed the publish function for the main application and logged the data information in globalState. Now, let’s go to the sub-application and use data to get user information and display it on the page, as follows.
import { singleSpaPropsSubject, SingleSpaProps, } from '.. /single-spa/single-spa-props'; @Component({ selector: 'iview-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less'], }) export class AppComponent { title = 'mango-iview'; state; subscription: Subscription; singleSpaProps: SingleSpaProps; count = 0; ngOnInit() { this.subscription = singleSpaPropsSubject.subscribe(async (props) => { props['onGlobalStateChange']((state, Prev) => {// state: changed state; This. state = state; Console. warn(' iView received value -state -->' + json.stringify (state)); Console. warn(' iView received value -prev -->' + json.stringify (prev)); this.countAdd(); }); Console. warn(' iView's initialization to receive parent value---->' + props); this.singleSpaProps = props; }); } // Display the number of values accepted by the child application async countAdd() {this.count++; console.log(this.count); } setGlobalState(data) {data++; This. SingleSpaProps ['setGlobalState']({micro: 'IView ', id: data,}); }}Copy the code
HTML is still simple
<div>
<hr />
<h1>Iview child application</h1>
<h1 (click) ="countAdd()">console</h1>
<button (click) ="setGlobalState(count)">The sub app sent a congratulatory message</button>
<div>state:{{ state | json }}</div>
<div>count:{{ count }}</div>
</div>
Copy the code
Finally, let’s look at the actual effect. We send data from the master application and sub-applications receive data rendering and can send data to the master application in a closed loop. The effect! (See below)
summary
Here, qiankun basic communication is completed! We implemented the observer in the main application, and the data published by the publishing function is stored in the globalState pool. When we enter the child application, we use singleSpaPropsSubject to get the singleSpaProps object and observer, and then use singleSpaProps to publish functions to notify the main application to complete the page data rendering!
Minor entanglements (plagued by technical problems welcome discussion)
Ps: Why hasn’t it been updated for so long? Because I found a small problem.
When the main application updates the globalState data state, the child application consoles the received value, but the page does not display it. You must click the console button on the page (HTML) to call console(){console.log(this.count); } method to display content in the child application page (code examples are also available).
A little suspect is the child application isolation or no use of the problem is not necessarily…
One last thing
If you’ve already seen it, please give it a thumbs up
Your likes are the greatest encouragement to the author, and can also let more people see this article!