美文网首页
微前端乾坤+Angular9

微前端乾坤+Angular9

作者: 没有注定的结局 | 来源:发表于2020-08-31 16:04 被阅读0次

    前言

    之前写过一篇关于微前端乾坤+Angular8的笔记,现在NG9已经到来,因此做了一次升级,仅以此文记录。

    安装依赖包

    ng add single-spa-angular@4 single-spa@5

    打包配置文件

    extra-webpack.config.js 同NG8

    修改main.single-spa.ts

    import { enableProdMode, NgZone, PlatformRef } from '@angular/core';
    
    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    import { Router } from '@angular/router';
    import { AppModule } from './app/app.module';
    import { environment } from './environments/environment';
    import { singleSpaAngular, getSingleSpaExtraProviders } from 'single-spa-angular';
    import { singleSpaPropsSubject, SingleSpaProps } from './single-spa/single-spa-props';
    
    if (environment.production) {
      enableProdMode();
    }
    
    // AppModule 只能引用一次,不然会报错
    const bootstrapFunction = (ref: PlatformRef) => ref.bootstrapModule(AppModule);
    
    // 单独运行的保障
    if (!(window as any).__POWERED_BY_QIANKUN__) {
      bootstrapFunction(platformBrowserDynamic()).catch((err) => console.error(err));
    }
    
    const { bootstrap, mount, unmount } = singleSpaAngular({
      bootstrapFunction: (singleSpaProps: SingleSpaProps) => {
        // 入参
        singleSpaPropsSubject.next(singleSpaProps);
        return bootstrapFunction(platformBrowserDynamic(getSingleSpaExtraProviders()));
      },
      template: '<app-root />',
      Router,
      NgZone,
    });
    
    export { bootstrap, mount, unmount };
    
    

    父项目入参处理

    修改定义

    修改 single-spa文件夹下的single-spa-props.ts文件

    import { ReplaySubject } from 'rxjs';
    import { AppProps } from 'single-spa';
    
    // Props 发生改变时的订阅
    export const singleSpaPropsSubject = new ReplaySubject<SingleSpaProps>(1);
    
    // Add any custom single-spa props you have to this type def
    // https://single-spa.js.org/docs/building-applications.html#custom-props
    export type SingleSpaProps = AppProps & {
      AccessToken: string; // 传入的参数定义
    };
    
    

    参数使用

    在app.component.ts中使用入参

      constructor(public sessionService: SessionService) {
        singleSpaPropsSubject.subscribe(
          (subProps: SingleSpaProps) => {
            if (!!subProps && !!subProps.AccessToken) {
              this.sessionService.AccessToken = subProps.AccessToken;
            }
          },
          (error) => {
            console.error(error);
          }
        );
      }
    

    其他

    在需要使用入参的地方视具体情况修改。

    相关文章

      网友评论

          本文标题:微前端乾坤+Angular9

          本文链接:https://www.haomeiwen.com/subject/zbvdrktx.html